1.pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.7.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
</dependencies>
2.配置类
package com.example.springsecuritytest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/loginUser/**").permitAll()
.antMatchers("/**").hasAnyAuthority("admin")
.anyRequest().authenticated();
http.formLogin().loginPage("/loginUser/noLogin");
http.logout().logoutUrl("/signOut").logoutSuccessUrl("/loginUser/signOutSuccess");
http.exceptionHandling().accessDeniedPage("/loginUser/fail");
http.csrf(csrf -> csrf.disable());
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
3.controller层
3.1用户controller
package com.example.springsecuritytest.controller;
import com.example.springsecuritytest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/loginUser")
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/login")
public String login(String username,String pwd){
return userService.login(username,pwd);
}
@RequestMapping("/noLogin")
public String noLogin(){
return "没有登录认证";
}
@RequestMapping("/signOutSuccess")
public String signOut(){
return "登出成功";
}
@RequestMapping("/fail")
public String fail(){
return "您无权进行此操作";
}
}
3.2测试controller
package com.example.springsecuritytest.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/test")
public String test(){
return "success";
}
@PostMapping("/select")
public String select(){
return "查询成功";
}
}
4.entity层
4.1用户类
package com.example.springsecuritytest.entity;
public class User {
private String username;
private String pwd;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
4.2 用户认证信息类
package com.example.springsecuritytest.entity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
public class UserDetail implements UserDetails {
private List<GrantedAuthority> authorities;
private User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getPassword() {
return user.getPwd();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setAuthorities(List<GrantedAuthority> authorities) {
this.authorities = authorities;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
5.service层
5.1用户登录service
package com.example.springsecuritytest.service;
public interface UserService {
public String login(String username,String pwd);
}
5.2用户登录service实现
package com.example.springsecuritytest.service;
import com.alibaba.fastjson.JSON;
import com.example.springsecuritytest.entity.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public String login(String username, String pwd) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,pwd);
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
if(Objects.isNull(authenticate)){
throw new RuntimeException("登陆失败!");
}
SecurityContextHolder.getContext().setAuthentication(authenticate);
UserDetail userDetail = (UserDetail)authenticate.getPrincipal();
return JSON.toJSONString(userDetail.getUser());
}
}
5.3 用户认证service
package com.example.springsecuritytest.service;
import com.example.springsecuritytest.entity.User;
import com.example.springsecuritytest.entity.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = getUserByUsername(username);
if(user == null){
throw new UsernameNotFoundException("用户名不存在");
}
user.setPwd(passwordEncoder.encode(user.getPwd()));
UserDetail userDetail = new UserDetail();
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(()-> "admin");
userDetail.setAuthorities(authorities);
userDetail.setUser(user);
return userDetail;
}
private User getUserByUsername(String username){
if("ttz".equals(username)){
User user = new User();
user.setUsername("ttz");
user.setPwd("980422");
return user;
}
return null;
}
}