栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring security登陆验证(方式2)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring security登陆验证(方式2)

基于springsession存储token并将token放置在header中
1、加依赖

        
            org.springframework.session
            spring-session-core
        

2、写配置文件

@Configuration
@EnableWebSecurity
@EnableSpringHttpSession
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                //设置所有人可以访问登录页
                .antMatchers("/").permitAll()
                .and().authorizeRequests()
                .anyRequest().permitAll()
                .and().formLogin()
                .loginPage("/").permitAll()
                .failureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setCharacterEncoding("UTF-8");
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                PrintWriter writer = response.getWriter();
                JSONObject jsonObject = new JSONObject();
                if (exception instanceof DisabledException) {
                    jsonObject.put("message", "账户被禁用,请联系管理员!");
                } else if (exception instanceof BadCredentialsException) {
                    jsonObject.put("message", "用户名或密码错误!");
                }
                writer.write(jsonObject.toJSONString());
                writer.flush();
                writer.close();
            }
        }).successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setCharacterEncoding("UTF-8");
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                //返回给前端的json对象,也可不返回
                PrintWriter writer = response.getWriter();
                writer.write(JSONObject.toJSONString(new JsonInfo(request.getSession().getId())));
                writer.flush();
                writer.close();
                //清除session中的认证信息
                clearAuthenticationAttributes(request);
            }
        })
                //暂时禁用csrf
                .and().csrf().disable();
    }

    //清除session中的认证信息
    private void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class JsonInfo {
        private String token;
    }

    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                //设置编码器
                .passwordEncoder(NoOpPasswordEncoder.getInstance())
                //添加测试用户和密码
                .withUser("123456").password("123456").roles("USER");
    }

    @Bean
    //将token存放到header里,不加这个方法header里就没x-auth-token参数
    public HeaderHttpSessionIdResolver httpSessionStrategy() {
        return new HeaderHttpSessionIdResolver("x-auth-token");
    }

    //存session时要时用到
    @Bean
    public MapSessionRepository sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }

}

3、调试结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014454.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号