springboot spring-security 集成微信登录

首先,感谢https://github.com/liyiorg/weixin-popular,使用了一些关于微信的代码,其次,参考了网上一些springboot springsecurity oauth2 登录的文章。

自己的代码,自己测试过,微信登录木有问题。配置一下自己的appid和secret就可以使用,如果有问题,可以给我留言。

github:https://github.com/luotuo/springboot-security-wechat

MyOAuth2RestTemplate这个类也改了很多,因为微信的登录基本不怎么按照套路出牌,各种在改参数,所以代码里面也只能改改改。。。
欢迎大家fork、star、pr
也欢迎留言

这个文件很重要

@Configuration
@EnableWebSecurity //启用web权限
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用方法验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
    @Autowired
    private OAuth2ClientContext oauth2ClientContext;

    @Resource
    private UserService userService;
    @Resource
    private UserWechatService userWechatService;
    @Resource
    private UserPrivilegeService userPrivilegeService;
    @Resource
    private PrivilegeConfigService privilegeConfigService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                //任何访问都必须授权
                .anyRequest().fullyAuthenticated()
                //配置那些路径可以不用权限访问
                .mvcMatchers("/login", "/login/wechat").permitAll()
                .and()
                .formLogin()
                //登陆成功后的处理,因为是API的形式所以不用跳转页面
                .successHandler(new MyAuthenticationSuccessHandler())
                //登陆失败后的处理
                .failureHandler(new MySimpleUrlAuthenticationFailureHandler())
                .and()
                //登出后的处理
                .logout().logoutSuccessHandler(new RestLogoutSuccessHandler())
                .and()
                //认证不通过后的处理
                .exceptionHandling()
                .authenticationEntryPoint(new RestAuthenticationEntryPoint());
        http.addFilterAt(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
        http.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        //http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //密码加密
        //return new BCryptPasswordEncoder(16);
        return new MyPasswordEncoder("2");
    }

    /**
     * 登出成功后的处理
     */
    public static class RestLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

        @Override
        public void onLogoutSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            //Do nothing!
        }
    }

    /**
     * 权限不通过的处理
     */
    public static class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request,
                             HttpServletResponse response,
                             AuthenticationException authException) throws IOException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    "Authentication Failed: " + authException.getMessage());
        }
    }

    @Bean
    public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }

    @Bean
    public Filter ssoFilter() {
        CompositeFilter filter = new CompositeFilter();
        List<Filter> filters = new ArrayList<>();
        filters.add(ssoFilter(wechat(), "/login/wechat"));
        filter.setFilters(filters);
        return filter;
    }

    @Bean
    public Filter ssoFilter(ClientResources client, String path) {
        MappingJackson2HttpMessageConverter customJsonMessageConverter = new
                MappingJackson2HttpMessageConverter();
        customJsonMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN));
        MyOAuth2ClientAuthenticationProcessingFilter filter = new MyOAuth2ClientAuthenticationProcessingFilter(path);
        filter.setAllowSessionCreation(true);
        MyOAuth2RestTemplate template = new MyOAuth2RestTemplate(client.getClient(), oauth2ClientContext);
        template.setMessageConverters(Arrays.asList(customJsonMessageConverter));
        filter.setRestTemplate(template);
        MyUserInfoTokenServices tokenServices = new MyUserInfoTokenServices(client.getResource().getUserInfoUri(),
                client.getClient().getClientId(),
                userService,
                userWechatService,
                userPrivilegeService,
                privilegeConfigService);
        tokenServices.setRestTemplate(template);
        filter.setTokenServices(tokenServices);
        return filter;
    }

    @Bean
    @ConfigurationProperties(prefix = "wechat")
    public ClientResources wechat() {
        return new ClientResources();
    }
}

class ClientResources {

    @NestedConfigurationProperty
    private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();

    @NestedConfigurationProperty
    private ResourceServerProperties resource = new ResourceServerProperties();

    public AuthorizationCodeResourceDetails getClient() {
        return client;
    }

    public ResourceServerProperties getResource() {
        return resource;
    }
}

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以,以下是一份关于您的Java SpringBoot项目的简介描述: 探索Java的SpringBoot魔法 亲爱的开发者们,准备好一起踏上这次深入Java的SpringBoot之旅了吗?如果您正在寻找一个现代化、高效且易于扩展的开发框架,那么这个SpringBoot项目将是您的理想选择。 主要特点: 快速开发:SpringBoot通过自动配置和约定大于配置的原则,大大简化了项目设置和开发过程。 易于扩展:SpringBoot与生俱来的灵活性使您可以轻松集成各种服务和数据库,以满足您日益增长的需求。 安全性:内置的安全特性,如OAuth2和Spring Security,确保您的应用程序安全无虞。 微服务支持:SpringBoot是微服务架构的理想选择,可以帮助您构建模块化、可扩展的应用程序。 社区支持:全球的开发者社区意味着您可以在遇到问题时找到大量的资源和支持。 无论您是初出茅庐的Java新手,还是经验丰富的开发者,这个项目都将为您提供一个深入了解SpringBoot的机会。无论您是想学习新的技能,还是想提高现有应用程序的性能,这个项目都将是您的宝贵资源。 内容概览 项目设置和初始化 控制器设计和实现 数据持久化与数据库集成 安全性和身份验证 性能优化和监控 部署和生产环境考虑 现在,是时候让您的Java技能得到充分发挥,并掌握SpringBoot的魔法了!这个项目将带领您从基础到高级,探索SpringBoot的每一个角落。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值