spring怎么加token
-
在Spring框架中添加Token可以通过以下步骤完成:
- 引入相关的依赖:首先,需要在你的项目中添加Spring Security的依赖。可以在项目的pom.xml文件中添加以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>- 配置Spring Security:接下来,需要配置Spring Security来启用Token验证功能。可以在项目的配置类上添加
@EnableWebSecurity注解,并实现WebSecurityConfigurerAdapter接口。在配置类中,可以使用configure(HttpSecurity http)方法来配置请求的安全策略,其中包括Token验证:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().permitAll() .and() .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } }- 实现Token验证逻辑:创建一个自定义的过滤器来处理Token验证逻辑。可以继承
AbstractAuthenticationProcessingFilter类,并重写attemptAuthentication(HttpServletRequest request, HttpServletResponse response)方法来实现Token的解析和验证。如果验证通过,可以使用getAuthenticationManager().authenticate(token)方法来建立用户的认证信息:
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public JwtAuthenticationFilter() { super("/api/**"); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String token = // 从请求中获取Token if (token != null) { Authentication authentication = getAuthenticationManager().authenticate(new JwtAuthenticationToken(token)); return authentication; } else { throw new JwtTokenMissingException("Missing JWT token"); } } }- 创建Token:在用户登录或认证成功后,可以生成Token并返回给客户端。可以使用JWT(JSON Web Token)来生成和验证Token。可以使用
io.jsonwebtoken包来实现JWT的相关功能。以下是生成Token的示例代码:
public class JwtTokenUtil { private static final String secret = "your-secret-key"; private static final long expirationTime = 86400000; // 1 day public static String generateToken(UserDetails userDetails) { Date now = new Date(); Date expirationDate = new Date(now.getTime() + expirationTime); return Jwts.builder() .setSubject(userDetails.getUsername()) .setIssuedAt(now) .setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } }- 配置Token的验证:在Token验证中,需要提供一个用于验证Token的Secret Key。可以将Secret Key存储在项目的配置文件中,然后在代码中读取配置。以下是将Secret Key存储在配置文件中的示例代码:
@Configuration @ConfigurationProperties(prefix = "jwt") public class JwtConfig { private String secret; // Getter and Setter // ... }# application.yml jwt: secret: your-secret-key- 在登录或认证成功后返回Token:在认证成功后,可以将生成的Token返回给客户端。可以在登录或认证成功的方法中,使用
Authentication对象获取用户信息,并调用JwtTokenUtil.generateToken(userDetails)方法来生成Token,然后返回给客户端:
public void login(HttpServletRequest request, HttpServletResponse response) { // 验证用户名和密码 // ... // 生成Token Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); String token = JwtTokenUtil.generateToken(userDetails); // 返回Token给客户端 response.setHeader("Authorization", "Bearer " + token); // ... }通过以上步骤,你就可以在Spring框架中成功添加Token验证功能了。当客户端发送请求时,需要在请求的Header中携带Token,服务器会根据Token进行验证并进行相应的处理。
1年前 -
在Spring中,我们可以通过以下几种方式来添加Token:
-
使用Spring Security:Spring Security是一个功能强大的安全框架,可以用于保护应用程序的身份验证和授权。它提供了一种称为CSRF(Cross-Site Request Forgery)保护的机制,可以防止跨站点请求伪造攻击。Spring Security的默认设置会自动在HTTP头部中添加一个名为X-XSRF-TOKEN的Token,并将其存储在Cookie中。在客户端发起POST、PUT、DELETE等需要修改服务器数据的请求时,需要将这个Token一并发送到服务器,服务器会验证这个Token是否有效。
-
自定义Token生成器:你可以通过自定义Token生成器来手动添加Token。首先,你需要实现一个Token生成器的接口,可以是一个Token服务类,也可以是一个自定义的过滤器。然后,在适当的时机(例如用户登录成功时),调用Token生成器来生成并存储Token。在需要验证Token的请求中,你需要获取请求中的Token,并与之前存储的Token进行比较来验证其有效性。
-
使用Spring Session:Spring Session是一个可以帮助你管理用户会话的框架,它可以将用户会话信息存储在不同的存储介质中,如内存、数据库、Redis等。在使用Spring Session时,你可以配置一个拦截器或过滤器来拦截请求,在其中生成并存储Token,并对请求进行验证。
-
使用JSON Web Token(JWT):JSON Web Token是一种开放标准(RFC 7519),它定义了一种紧凑、自包含的方式来安全地在各方之间传输信息。在Spring中,你可以使用相关的库来实现JWT的生成和验证。在生成Token时,你可以将一些用户信息加密到Token中,并在请求中将Token作为身份验证的凭证发送到服务器。
-
使用Spring MVC的框架支持:Spring MVC框架提供了一些支持防止CSRF攻击的功能。你可以通过在表单上添加一个隐藏字段,然后在请求处理方法中通过Spring MVC的标记来获取Token,并在处理方法中进行验证。使用这种方式可以比较简单地实现Token的添加和验证。
1年前 -
-
要在Spring中添加Token认证机制,可以按照以下步骤进行操作:
- 引入相关依赖
在Spring项目中,首先需要引入相关的依赖。可以通过Maven或Gradle等包管理工具在项目的构建文件中添加以下依赖:
<!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- JSON Web Token --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.0</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.0</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.0</version> </dependency>- 创建Token工具类
接下来,创建一个Token工具类,用于生成和解析Token。可以使用JJWT库来实现。在工具类中,可以编写以下方法:
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; @Component public class TokenUtils { private static final long EXPIRATION_TIME = 86400_000; // 过期时间为一天 private static final String SECRET = "secret"; // 用于签名Token的密钥 /** * 生成Token */ public String generateToken(String username) { Map<String, Object> claims = new HashMap<>(); claims.put("sub", username); claims.put("iat", new Date()); claims.put("exp", new Date(System.currentTimeMillis() + EXPIRATION_TIME)); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, SECRET) .compact(); } /** * 解析Token,获取用户名 */ public String getUsernameFromToken(String token) { Claims claims = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody(); return claims.getSubject(); } /** * 检查Token是否过期 */ public boolean isTokenExpired(String token) { Date expiration = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody() .getExpiration(); return expiration.before(new Date()); } }- 创建Token认证过滤器
创建一个Token认证过滤器,用于验证请求中的Token。可以创建一个实现了OncePerRequestFilter的类,并重写doFilterInternal方法。在该方法中,可以读取请求头中的Token,并使用Token工具类来校验Token的有效性。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.web.server.ResponseStatusException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Configuration public class TokenAuthenticationFilter extends BasicAuthenticationFilter { @Autowired private TokenUtils tokenUtils; @Autowired private MyUserDetailsService userDetailsService; public TokenAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String token = request.getHeader("Authorization"); if (token != null && token.startsWith("Bearer ")) { token = token.substring(7); if (tokenUtils.isTokenExpired(token)) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Token expired"); } String username = tokenUtils.getUsernameFromToken(token); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } chain.doFilter(request, response); } }- 配置Spring Security
在Spring Security配置类中,添加Token认证的配置。可以继承WebSecurityConfigurerAdapter,并重写configure方法。在方法中,可以配置登录和访问路径、添加Token认证过滤器等。
import org.springframework.beans.factory.annotation.Autowired; 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.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.core.userdetails.UserDetailsService; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private TokenAuthenticationFilter tokenAuthenticationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() // 允许/login路径的访问 .anyRequest().authenticated() .and() .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }- 使用Token认证
现在,就可以在需要进行认证的接口上使用Token认证了。可以在需要进行认证的Controller方法上添加@PreAuthorize注解,指定需要的权限。
例如:
@RestController public class MyController { @Autowired private TokenUtils tokenUtils; @GetMapping("/hello") @PreAuthorize("hasRole('ROLE_USER')") // 需要ROLE_USER角色才能访问 public String hello(@RequestHeader("Authorization") String tokenHeader) { String token = tokenHeader.substring(7); // 去掉"Bearer "前缀 String username = tokenUtils.getUsernameFromToken(token); return "Hello, " + username; } }这样,当请求
/hello接口时,会首先进行Token认证,如果Token有效且权限匹配,则可以正常访问接口。以上就是在Spring中添加Token认证机制的步骤。通过引入相关依赖、编写Token工具类、创建Token认证过滤器和配置Spring Security,可以实现基于Token的认证机制。
1年前 - 引入相关依赖