Spring security oauth2 and form login configuration

后端 未结 1 770
你的背包
你的背包 2020-12-08 05:21

My project consists exposes two different parts, a JSF admin panel and a RESTfull service. I am trying to setup spring security to use different authentication methods depen

相关标签:
1条回答
  • 2020-12-08 06:00

    I tried to adapt your security configuration. Unfortunately, I can not validate this configuration due to missing reference application.

    Maybe it can help you:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserRepository userRepository;
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(new UserDetailsService() {
                @Override
                public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                    User user = userRepository.findOneByUsername(s);
    
                    if (null == user) {
                        throw new UsernameNotFoundException("The user with email " + s + " was not found");
                    }
    
                    return (UserDetails) user;
                }
            }).passwordEncoder(passwordEncoder);
        }
    
        @Override
        public void configure(WebSecurity webSecurity) throws Exception {
            webSecurity
                    .ignoring()
                    .antMatchers("/resources/**"
                            , "/templates/**"
                            , "/login"
                            , "/logout"
                            , "/ui/**"
                            , "/401.html"
                            , "/404.html"
                            , "/500.html");
        }
    
        @Configuration
        @EnableAuthorizationServer
        public static class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
    
            @Autowired
            private AuthenticationManager authenticationManager;
    
            @Bean
            public JwtAccessTokenConverter accessTokenConverter() {
                return new JwtAccessTokenConverter();
            }
    
            @Override
            public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
                oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
            }
    
            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
                endpoints.authenticationManager(authenticationManager).accessTokenConverter(accessTokenConverter());
            }
    
    
            @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.inMemory()
                        .withClient("xxx")
                        .resourceIds("xxx")
                        .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                        .scopes("read", "write", "trust", "update")
                        .accessTokenValiditySeconds(xxx)
                        .refreshTokenValiditySeconds(xxx)
                        .secret("xxx");
    
            }
        }
    
        @Configuration
        @Order(1)
        public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
            @Override
            public void configure(HttpSecurity http) throws Exception {
                http
                        .csrf().disable()
                        .authorizeRequests()
                        .antMatchers("/ui/admin.xhtml").hasAnyAuthority("admin", "ADMIN")
                        .antMatchers("/thymeleaf").hasAnyAuthority("admin", "ADMIN")
                        .and()
                        .formLogin()
                        .loginPage("/login")
                        .defaultSuccessUrl("/ui/index.xhtml")
                        .failureUrl("/login?error=1")
                        .permitAll()
                        .and()
                        .logout()
                        .permitAll()
                        .and()
                        .rememberMe()
                        .and().exceptionHandling().accessDeniedPage("/error/403");
            }
        }
    
        @Order(2)
        @Configuration
        @EnableResourceServer
        public static class CustomResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
    
            @Bean
            ApplicationListener<AbstractAuthorizationEvent> loggerBean() {
                return new AuthenticationLoggerListener();
            }
    
            @Bean
            AccessDeniedHandler accessDeniedHandler() {
                return new AccessDeniedExceptionHandler();
            }
    
            @Bean
            AuthenticationEntryPoint entryPointBean() {
                return new UnauthorizedEntryPoint();
            }
    
            @Override
            public void configure(HttpSecurity http) throws Exception {
                ContentNegotiationStrategy contentNegotiationStrategy = http.getSharedObject(ContentNegotiationStrategy.class);
                if (contentNegotiationStrategy == null) {
                    contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
                }
                MediaTypeRequestMatcher preferredMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy,
                        MediaType.APPLICATION_FORM_URLENCODED,
                        MediaType.APPLICATION_JSON,
                        MediaType.MULTIPART_FORM_DATA);
    
                http.authorizeRequests()
                        .and()
                        .anonymous().disable()
                        .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                        .and().httpBasic()
                        .and()
                        .exceptionHandling()
                        .accessDeniedHandler(accessDeniedHandler()) // handle access denied in general (for example comming from @PreAuthorization
                        .authenticationEntryPoint(entryPointBean()) // handle authentication exceptions for unauthorized calls.
                        .defaultAuthenticationEntryPointFor(entryPointBean(), preferredMatcher)
                        .and()
                        .authorizeRequests()
                        .antMatchers("/api/**").fullyAuthenticated();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题