Spring security- Send credentials as json instead of regular form in rest service

后端 未结 2 527
轻奢々
轻奢々 2020-12-17 03:44

I am writing rest service with json. For backend I use Spring Security. I have form witch sends with ajax rest object as follow:

2条回答
  •  悲&欢浪女
    2020-12-17 04:28

    You can extend and override WebSecurityConfigurerAdapter

    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .csrf().disable()
                .addFilter(new UserNamePasswordAuthFilter(authenticationManager(), userRepo))
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(daoAuthenticationProvider());
        }
        
        @Bean
        public DaoAuthenticationProvider daoAuthenticationProvider() {
            DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
            provider.setUserDetailsService(userDetailsService); // custom user service
            provider.setPasswordEncoder(passwordEncoder); // custom password encoder
            return provider;
        }
    

    Then you can define a filter for authentication and optionally you can override successful login behavior.

    public class UserNamePasswordAuthFilter extends UsernamePasswordAuthenticationFilter {
    
        private final AuthenticationManager authManager;
        private final AecUserRepo userRepo;
        
        public UserNamePasswordAuthFilter(AuthenticationManager authManager, AecUserRepo userRepo) {
            super();
            this.authManager = authManager;
            this.userRepo = userRepo;
        }
    
        @Override
        public Authentication attemptAuthentication(HttpServletRequest request,
                HttpServletResponse response) throws AuthenticationException {
    
            try {
                // Get username & password from request (JSON) any way you like
                UsernamePassword authRequest = new ObjectMapper()
                        .readValue(request.getInputStream(), UsernamePassword.class);
                
                Authentication auth = new UsernamePasswordAuthenticationToken(authRequest.getUsername(), 
                        authRequest.getPassword());
                
                return authManager.authenticate(auth);
            } catch (Exception exp) {
                throw new RuntimeException(exp);
            }
        }
        
        @Override
        protected void successfulAuthentication(HttpServletRequest request,
                HttpServletResponse response, FilterChain chain, Authentication authResult)
                throws IOException, ServletException {
    
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
                        + authResult);
            }
    
            // custom code
            
            SecurityContextHolder.getContext().setAuthentication(authResult);       
        }
    }
    

提交回复
热议问题