SpringSecurity-学习2

这里开始写SpringSecurity在前后端分离时的:

1.认证成功时的Handler

successHandler

2.认证失败时的Handler

failureHandler

3.注销时的Handler

logoutSuccessHandler

4.请求未认证时的Handler

exceptionHandling(exception -> {
    exception.authenticationEntryPoint})

5.会话并发处理

http.sessionManagement(session -> {
session.maximumSessions(1) //设置session最多的数量,最大并发数
.expiredSessionStrategy(new MySessionInformationExpiredStrategy()); //会话过期
});
配置类我统一写在了文章的最后==============================================================================================================================================================================================

 1.认证成功时的Handler

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //用户身份信息
        Object principal = authentication.getPrincipal();
        //用户凭证信息  ---  密码
        Object credentials = authentication.getCredentials();
        //用户权限信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        HashMap result = new HashMap();
        result.put("code", "200");
        result.put("msg", "success");
        result.put("data", authentication);
        result.put("用户身份信息", principal);
        result.put("密码", credentials);
        //将结果转成JSON字符串
        String json = JSON.toJSONString(result);

        //响应头
        response.setContentType("application/json;charset=utf-8");
        //响应体
        response.getWriter().println(json);
    }
}

2.认证失败时的Handler

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        //登录失败本地信息
        String localizedMessage = exception.getLocalizedMessage();

        HashMap result = new HashMap();
        result.put("code", "400");
        result.put("msg", "登录失败");
        result.put("data", localizedMessage);
        //将结果转成JSON字符串
        String json = JSON.toJSONString(result);

        //响应头
        response.setContentType("application/json;charset=utf-8");
        //响应体
        response.getWriter().println(json);
    }
}

3.注销时的Handler

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //创建结果对象
        HashMap result = new HashMap();
        result.put("code", "0");
        result.put("msg","注销成功");
        //转换成JSON字符串
        String json = JSON.toJSONString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);

    }
}

4.请求未认证时的Handler

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        HashMap result = new HashMap();
        result.put("code", HttpServletResponse.SC_UNAUTHORIZED);
//        result.put("msg", authException.getMessage());
        result.put("msg", "需要登录");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(JSON.toJSONString(result));

    }
}

5.会话并发处理

 

public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        //创建结果对象
        HashMap result = new HashMap();
        result.put("code", -1);
        result.put("message", "该账号已从其他设备登录");

        //转换成json字符串
        String json = JSON.toJSONString(result);

        HttpServletResponse response = event.getResponse();
        //返回响应
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}

 

 

 

重写完上面各个Handler后得去SpringSecurity的配置类里配置相关信息才能生效:

@Configuration
//开启SpringSecurity的自定义配置
@EnableWebSecurity
public class WebSecurityConfig {
    //默认配置
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //authorizeRequests():开启授权保护
        //anyRequest():对所有请求开启授权保护
        //authenticated():已认证请求会自动被授权
        http
                .authorizeRequests(authorize -> authorize
                        //对所有请求开启授权保护
                        .anyRequest()
                        //已认证的请求会自动授权
                        .authenticated()
                )
                .formLogin(from -> {              //表单授权方式
                    from.loginPage("/login").permitAll()                     //permitAll表示无需授权可访问
                            .usernameParameter("username").passwordParameter("password")       //自定义用户名密码的参数名
                            .failureUrl("/login?error")                    //自定义校验错误后的URL值

                            .successHandler(new MyAuthenticationSuccessHandler())         //认证成功时的处理
                            .failureHandler(new MyAuthenticationFailureHandler())         //认证失败时的处理
                            ;
                });
        //注销成功时的处理
        http.logout(logout -> logout.logoutSuccessHandler(new MyLogoutSuccessHandler()));
        //请求未认证处理
        http.exceptionHandling(exception -> {
            exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());
        });
        //开启跨域
        http.cors(withDefaults());
    
        http.sessionManagement(session -> {
            session.maximumSessions(1)   //设置session最多的数量,最大并发数
            .expiredSessionStrategy(new MySessionInformationExpiredStrategy());   //会话过期
        });
// .httpBasic(withDefaults());//基本授权方式
//关闭csrf防御 http.csrf((csrf) -> { csrf.disable(); }); return http.build(); } }

 

posted @ 2025-04-10 15:05  lksses  阅读(22)  评论(0)    收藏  举报