spring Securityは前後端が分離され、先端はjsonで問題を登録し、バックエンドはtokenに戻る.

23127 ワード

spring Security配置
   protected void configure(HttpSecurity http) throws Exception {

        http.cors().and()
                .authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .and().csrf().disable()
                //     filter  UsernamePasswordAuthenticationFilter
                .addFilterAt(usernamePasswordFilter(),UsernamePasswordAuthenticationFilter.class)
//                .addFilterBefore(responseFilter(), ChannelProcessingFilter.class)
                .addFilterBefore( getTokenValidateFilter(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/login_url","/logout_url").permitAll()
                .anyRequest().authenticated()
                .and()
//                .formLogin().loginPage("/login_url").loginProcessingUrl("/login_url").failureUrl("/fail_url")
//                .successHandler(getLoginSuccessHandler())
//                .and()
                .logout().logoutUrl("/logout_url")
                .logoutSuccessHandler(getLogoutSuccessHandler());

    }
     @Bean
    public LoginSuccessHandler getLoginSuccessHandler(){
        return new LoginSuccessHandler();
    }
    
    @Bean
    public UsernamePasswordFilter usernamePasswordFilter() throws Exception {
        UsernamePasswordFilter filter=new UsernamePasswordFilter();
        filter.setAuthenticationManager(super.authenticationManager());
        filter.setFilterProcessesUrl("/login_url");
        filter.setAuthenticationSuccessHandler(getLoginSuccessHandler());
        return filter;
    }

UsernamePassword Authentication Filter類を書き換えて、彼に伝来したのはjsonであると判断させます.
public class UsernamePasswordFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
            String username=null;
            String password=null;
            try{
            // inputStream  ·   
                Map<String,String > map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                username =map.get("username");
                password=map.get("password");
            }catch (IOException e){
                throw new MyDefineException(405,"        ");
            }
            if(username==null){ throw new MyDefineException(405,"     ");};
            if(password==null){throw new MyDefineException(405,"    ");}
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }

        return super.attemptAuthentication(request, response);
    }
}
LoginsSuccess Handler類の登録が成功した後の処理はここでtokenに戻り、ユーザー情報を保存します.
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    Logger log = LoggerFactory.getLogger(LoginSuccessHandler.class);
    //  springSecurity UserDetailSevice  
    @Resource
    EmployeeDetailService employeeDetailService;
	//              ,    
    @Resource
    EmployeeRepository employeeRepository;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    //                
        final Employee employee = (Employee) employeeDetailService.loadUserByUsername(authentication.getName());
        log.info("      ");
        //  jwt     token,       jwt    
        final String token = JwtTokenUtil.generateToken(employee);
        employeeRepository.insert(employee);

        returnToken(httpServletResponse,token);
    }
    public void returnToken(HttpServletResponse response,String token) throws IOException {
    //        
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        CommonResult<Map<String, String>> mapCommonResult = new CommonResult<>(200,"    ",map);
        writer.write(JSON.toJSONString(mapCommonResult));
        writer.flush();
    }
}