- 1.集中式版
- 1.1.整合认证第一版
- 1.1.1.搭建SpringBoot环境
- 1.1.2.加入Spring Security
- 1.2.整合认证第二版【加入jsp使用自定义认证页面】
- 1.2.1.加入自定义的jsp页面
- 1.2.2.提供SpringSecurity配置类
- 1.2.3.修改相应的控制器方法并配置视图解析器
- 1.2.4.使用tomcat插件启动项目
- 1.3.整合认证第三版【数据库认证】
- 1.3.1.加入通用mapper
- (1)导入数据库操作相关jar包
- (2)在application.yml配置文件中添加数据库操作相关配置
- (3)在启动类上添加扫描dao接口包注解
- 1.3.2.使用数据库实现认证
- (1)创建角色和用户的pojo对象(直接使用SpringSecurity的角色规范)
- (2)提供角色和用户的mapper接口
- (3)提供认证service接口以及实现类
- (4)修改配置类WebSecurityConfig
- 1.3.3.使用数据库中的用户信息进行测试
- 1.4.整合实现授权功能
- 1.4.1.在配置类上添加开启方法级的授权注解
- 1.4.2.在产品控制器类上添加注解
- 1.4.3.进行测试
- 2.分布式版
- 2.1.分布式认证
- 2.1.1.分布式认证概念说明
- 2.1.2.分布式认证流程图
- 2.1.3.JWT介绍
- 2.2.创建父工程与common工具模块
- 2.3.相关准备工作
- 2.4.认证模块搭建
- 2.5.资源服务器搭建
本文章的笔记整理来自黑马视频https://www.bilibili.com/video/BV1vt4y1i7zA?p=33,相关资料可以在该视频的评论区进行获取
注:如果对Spring Security不是很了解的读者,可以先去阅读Spring Security——入门介绍这篇文章。
1.集中式版 1.1.整合认证第一版 1.1.1.搭建SpringBoot环境(1)在IDEA中创建一个名为spring_security_family空项目
(2)创建一个新的Module
(3)导入SpringBoot相关的jar包
4.0.0 com.itheima springboot_security_jsp 1.0-SNAPSHOT war org.springframework.boot spring-boot-starter-parent 2.1.3.RELEASE org.springframework.boot spring-boot-starter-web
(4)创建SpringBoot启动类以及SpringBoot全局配置文件application.yml
package com.itheima;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//SpringBoot启动类
@SpringBootApplication
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class);
}
}
# application.yml server: port: 8080
(5)测试
package com.itheima.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/product")
public class ProductController {
@RequestMapping
@ResponseBody
public String findAll(){
return "success";
}
}
先在SpringBoot启动类中启动SpringBoot,然后在浏览器地址栏中输入http://localhost:8080/product,如果得到下面的结果,则说明测试成功。
(1)在pom.xml中加入Spring Security依赖
org.springframework.boot spring-boot-starter-security
(2)然后进行测试,当在浏览器地址栏中输入http://localhost:8080/product时,出现如下界面(由Spring Security提供):
这说明Spring Security已经加入到项目中了,此时可以使用默认的用户名user,以及在项目控制台动态生成的密码进行登录,然后就可以正常访问了。
(1)要想在SpringBoot中使用jsp页面,需要导入以下两个jar包,并且SpringBoot启动类不再生效。
org.springframework.boot spring-boot-starter-tomcat org.apache.tomcat.embed tomcat-embed-jasper
(2)在main目录下创建webapp目录,并导入需要的静态资源(相关资源在黑马视频的评论区进行获取)
(3)修改login.jsp中认证的url地址以及header.jsp中退出登录的url地址
package com.itheima.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//SpringSecurity配置信息
//指定认证对象的来源
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}123")
.roles("USER");
}
public void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/login.jsp", "failer.jsp", "/css
@Data
public class Payload {
private String id;
private T userInfo;
private Date expiration;
}
package com.itheima.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public static final ObjectMapper mapper = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String toString(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return mapper.writevalueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出错:" + obj, e);
return null;
}
}
public static T toBean(String json, Class tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static List toList(String json, Class eClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static Map toMap(String json, Class kClass, Class vClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static T nativeRead(String json, TypeReference type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
package com.itheima.utils;
import com.itheima.domain.Payload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.base64;
import java.util.UUID;
public class JwtUtils {
private static final String JWT_PAYLOAD_USER_KEY = "user";
public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusMinutes(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
private static Jws parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
private static String createJTI() {
return new String(base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
}
public static Payload getInfoFromToken(String token, PublicKey publicKey, Class userType) {
Jws claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload claims = new Payload<>();
claims.setId(body.getId());
claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
claims.setExpiration(body.getExpiration());
return claims;
}
public static Payload getInfoFromToken(String token, PublicKey publicKey) {
Jws claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload claims = new Payload<>();
claims.setId(body.getId());
claims.setExpiration(body.getExpiration());
return claims;
}
}
package com.itheima.utils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.base64;
public class RsaUtils {
private static final int DEFAULT_KEY_SIZE = 2048;
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
private static PublicKey getPublicKey(byte[] bytes) throws Exception {
bytes = base64.getDecoder().decode(bytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
bytes = base64.getDecoder().decode(bytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
publicKeyBytes = base64.getEncoder().encode(publicKeyBytes);
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
privateKeyBytes = base64.getEncoder().encode(privateKeyBytes);
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
}
在测试方法中生成公钥和私钥
package com.itheima.utils;
import org.junit.Test;
public class RsaUtilsTest {
private String privateFilePath = "E:\auth_key\id_key_rsa";
private String publicFilePath = "E:\auth_key\id_key_rsa.pub";
@Test
public void generateKey() throws Exception {
RsaUtils.generateKey(publicFilePath, privateFilePath, "itheima", 2048);
}
@Test
public void getPublicKey() throws Exception {
System.out.println(RsaUtils.getPublicKey(publicFilePath));
}
@Test
public void getPrivateKey() throws Exception {
System.out.println(RsaUtils.getPrivateKey(privateFilePath));
}
}
2.4.认证模块搭建
(1)创建一个名为heima-auth_server的认证模块
(2)导入相关依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-security com.itheima heima_common 1.0-SNAPSHOT mysql mysql-connector-java 5.1.47 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0
(3)SpringBoot全局配置文件application.yml
server:
port: 9001
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: 123456
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
rsa:
key:
pubKeyFile: D:auth_keyid_key_rsa.pub
priKeyFile: D:auth_keyid_key_rsa
(4)创建配置类RsaKeyProperties
package com.itheima.config;
import com.itheima.utils.RsaUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.security.PrivateKey;
import java.security.PublicKey;
//配置类
@ConfigurationProperties("rsa.key")
public class RsaKeyProperties {
private String pubKeyFile;
private String priKeyFile;
private PublicKey publicKey;
private PrivateKey privateKey;
@PostConstruct
public void createRsaKey() throws Exception {
publicKey = RsaUtils.getPublicKey(pubKeyFile);
privateKey = RsaUtils.getPrivateKey(priKeyFile);
}
public String getPubKeyFile() {
return pubKeyFile;
}
public void setPubKeyFile(String pubKeyFile) {
this.pubKeyFile = pubKeyFile;
}
public String getPriKeyFile() {
return priKeyFile;
}
public void setPriKeyFile(String priKeyFile) {
this.priKeyFile = priKeyFile;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
}
(5)创建SpringBoot启动类AuthServerApplication
package com.itheima.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
//SpringBoot启动类
@SpringBootApplication
@MapperScan("com.itheima.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class,args);
}
}
(6)将集中式版本中domain、controller、service、mapper包中的代码复制过来,并作适当修改。
(7)重写认证的过滤器
package com.itheima.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.config.RsaKeyProperties;
import com.itheima.domain.SysRole;
import com.itheima.domain.SysUser;
import com.itheima.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
private RsaKeyProperties prop;
public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
this.authenticationManager = authenticationManager;
this.prop = prop;
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
return authenticationManager.authenticate(authRequest);
}catch (Exception e){
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
resultMap.put("msg", "用户名或密码错误!");
out.write(new ObjectMapper().writevalueAsString(resultMap));
out.flush();
out.close();
}catch (Exception outEx){
outEx.printStackTrace();
}
throw new RuntimeException(e);
}
}
public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
SysUser user = new SysUser();
user.setUsername(authResult.getName());
user.setRoles((List) authResult.getAuthorities());
String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
response.addHeader("Authorization", "Bearer "+token);
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_OK);
resultMap.put("msg", "认证通过!");
out.write(new ObjectMapper().writevalueAsString(resultMap));
out.flush();
out.close();
}catch (Exception outEx){
outEx.printStackTrace();
}
}
}
(8)验证认证的过滤器
package com.itheima.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.config.RsaKeyProperties;
import com.itheima.domain.Payload;
import com.itheima.domain.SysUser;
import com.itheima.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class JwtVerifyFilter extends BasicAuthenticationFilter {
private RsaKeyProperties prop;
public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
super(authenticationManager);
this.prop = prop;
}
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
//如果携带错误的token,则给用户提示请登录!
chain.doFilter(request, response);
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
resultMap.put("msg", "请登录!");
out.write(new ObjectMapper().writevalueAsString(resultMap));
out.flush();
out.close();
} else {
//如果携带了正确格式的token要先得到token
String token = header.replace("Bearer ", "");
//验证tken是否正确
Payload payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);
SysUser user = payload.getUserInfo();
if(user!=null){
UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
}
}
}
(9)配置类编写
package com.itheima.config;
import com.itheima.filter.JwtLoginFilter;
import com.itheima.filter.JwtVerifyFilter;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private RsaKeyProperties prop;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//指定认证对象的来源
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest()
.authenticated()
.and()
.addFilter(new JwtLoginFilter(super.authenticationManager(), prop))
.addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
(10)测试
① 模拟登录,并获取登录成功后生成的token
② 查询产品列表
(1)创建资源服务器模块
(2)在pom.xml中导入相关的依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-security com.itheima heima_common 1.0-SNAPSHOT mysql mysql-connector-java 5.1.47 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0
(3)在SpringBoot全局配置文件application.yml中进行配置
server:
port: 9002
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: 123456
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
rsa:
key:
pubKeyFile: E:auth_keyid_key_rsa.pub
(4)编写SpringBoot启动类
package com.itheima;
import com.itheima.config.RsaKeyProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@MapperScan("com.itheima.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthSourceApplication {
public static void main(String[] args) {
SpringApplication.run(AuthSourceApplication.class, args);
}
}
(5)复制认证服务中的用户对象,角色对象和校验认证的接口
(6)复制认证服务中SpringSecurity配置类做修改(去掉“增加自定义认证过滤器”即可!)
package com.itheima.config;
import com.itheima.filter.JwtVerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties prop;
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest()
.authenticated()
.and()
.addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
(7)编写产品控制器方法
package com.itheima.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/product")
public class ProductController {
@Secured("ROLE_PRODUCT")
@RequestMapping("/findAll")
public String findAll(){
return "产品列表查询成功!";
}
}
此时目录结构如下图:
(8)测试(之前登录生成的token还未失效)
这里可以看出,当端口号为9002,并且在进行产品管理请求时,携带之前登录生成的token,便可以无需登录而请求成功,这样就简单地实现了分布式的认证。



