springboot spring-security 통합 위챗 로그인

6089 단어 기타
먼저 고맙습니다https://github.com/liyiorg/weixin-popular, 위챗에 대한 코드를 사용했고 그 다음에 인터넷에서springbootspringsecurityoauth2 로그인한 글을 참고했다.
자신의 코드, 자신이 테스트한 위챗 로그인 나무에 문제가 있습니다.자신의 appid와 시크릿을 설정하면 사용할 수 있습니다. 문제가 있으면 저에게 메시지를 남겨주세요.
github:https://github.com/luotuo/springboot-security-wechat
MyOAuth2 Rest Template라는 종류도 많이 바뀌었다. 위챗의 로그인은 기본적으로 규칙에 따라 카드를 내지 않기 때문에 각종 매개 변수를 바꾸고 있기 때문에 코드 안에서도 고칠 수밖에 없다.반갑습니다. 포크, 스타, 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 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;
    }
}

좋은 웹페이지 즐겨찾기