目录
一、实现前后端分离
1.1、导入pom依赖
XML
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.40</version>
</dependency>
1.2、认证成功处理
java
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//获取用户身份信息
Object principal = authentication.getPrincipal();
HashMap map = new HashMap<>();
map.put("code",200);
map.put("message","登录成功");
map.put("data",principal);
//将信息json化
String jsonString = JSON.toJSONString(map);
//返回json数据到前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonString);
}
}
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests(
authorize -> authorize
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
)
.formLogin(
//Customizer.withDefaults()
form -> form.loginPage("/login")
.permitAll()//无需授权就能访问
.usernameParameter("name")
.passwordParameter("pass")
.successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
);//使用表单授权方式
//.httpBasic(Customizer.withDefaults());//使用基本授权方式
httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能
return httpSecurity.build();
}
1.3、认证失败处理
java
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
String localizedMessage = exception.getLocalizedMessage();
HashMap map = new HashMap<>();
map.put("code",400);
map.put("message",localizedMessage);
//将信息json化
String jsonString = JSON.toJSONString(map);
//返回json数据到前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonString);
}
}
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests(
authorize -> authorize
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
)
.formLogin(
//Customizer.withDefaults()
form -> form.loginPage("/login")
.permitAll()//无需授权就能访问
.usernameParameter("name")
.passwordParameter("pass")
.successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
);//使用表单授权方式
//.httpBasic(Customizer.withDefaults());//使用基本授权方式
httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能
return httpSecurity.build();
}
1.4、用户注销处理
java
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
HashMap map = new HashMap<>();
map.put("code",200);
map.put("message","注销成功");
//将信息json化
String jsonString = JSON.toJSONString(map);
//返回json数据到前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonString);
}
}
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests(
authorize -> authorize
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
);
httpSecurity.formLogin(
//Customizer.withDefaults()//使用表单授权方式
//.httpBasic(Customizer.withDefaults());//使用基本授权方式
form -> form.loginPage("/login")
.permitAll()//无需授权就能访问
.usernameParameter("name")
.passwordParameter("pass")
.successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
);
httpSecurity.logout(logout ->
logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
);
httpSecurity.csrf(
csrf -> csrf
.disable()
);//关闭csrf功能
return httpSecurity.build();
}
1.5、请求未认证处理
java
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
String localizedMessage = authException.getLocalizedMessage();
HashMap map = new HashMap<>();
map.put("code",400);
map.put("message",localizedMessage);
//将信息json化
String jsonString = JSON.toJSONString(map);
//返回json数据到前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonString);
}
}
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests(
authorize -> authorize
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
);
httpSecurity.formLogin(
//Customizer.withDefaults()//使用表单授权方式
//.httpBasic(Customizer.withDefaults());//使用基本授权方式
form -> form.loginPage("/login")
.permitAll()//无需授权就能访问
.usernameParameter("name")
.passwordParameter("pass")
.successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
);
httpSecurity.logout(logout ->
logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
);
httpSecurity.exceptionHandling(exception ->
exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理
httpSecurity.csrf(
csrf -> csrf.disable()
);//关闭csrf功能
return httpSecurity.build();
}
1.6、跨域处理
java
httpSecurity.cors(Customizer.withDefaults());//跨域处理
1.7、用户认证信息处理
java
@RestController
public class IndexController {
@GetMapping("/")
public Map index(){
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
Object principal = authentication.getPrincipal();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
HashMap map = new HashMap<>();
map.put("principal",principal);
map.put("权限",authorities);
return map;
}
}
1.8、会话并发处理
java
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
HashMap map = new HashMap<>();
map.put("code",400);
map.put("message","账号已在其他地方登录");
//将信息json化
String jsonString = JSON.toJSONString(map);
HttpServletResponse response = event.getResponse();
//返回json数据到前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonString);
}
}
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.sessionManagement(session ->
session.maximumSessions(1)
.expiredSessionStrategy(new MySessionInformationExpiredStrategy())
);//会话并发处理
httpSecurity.cors(Customizer.withDefaults());//跨域处理
httpSecurity.authorizeRequests(
authorize -> authorize
.anyRequest() //对所有请求开启授权保护
.authenticated() //已认证的请求会自动授权
);
httpSecurity.formLogin(
//Customizer.withDefaults()//使用表单授权方式
//.httpBasic(Customizer.withDefaults());//使用基本授权方式
form -> form.loginPage("/login")
.permitAll()//无需授权就能访问
.usernameParameter("name")
.passwordParameter("pass")
.successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理
.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理
);
httpSecurity.logout(logout ->
logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理
);
httpSecurity.exceptionHandling(exception ->
exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理
httpSecurity.csrf(
csrf -> csrf.disable()
);//关闭csrf功能
return httpSecurity.build();
}