springboot+security+jwt+redis 实现微信小程序登录及token权限鉴定

1

springboot+security+jwt+redis 实现微信小程序登录及token权限鉴定

SpringBoot+Security+JWT+Redis 实现微信小程序登录及Token权限鉴定

项目配置首先,我们需要在 `pom.xml` 文件中添加必要的依赖:

```xml

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-security

io.jsonwebtoken

jjwt-api

io.jsonwebtoken

jjwt-impl

io.jsonwebtoken

jjwt-generator

org.springframework.boot

spring-boot-starter-data-redis

org.projectlombok

lombok

true

```

application.yml在 `application.yml` 文件中,我们需要配置 Redis 的连接信息:

```ymlspring:

redis:

host: localhost port:6379 password: your-redis-password```

security相关配置 Security核心配置类创建一个名为 `SecurityConfig.java` 的类,用于配置 Spring Security:

```java@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired private UserDetailsService userDetailsService;

@Override protected void configure(HttpSecurity throws Exception {

.antMatchers("/login").permitAll()

.anyRequest().authenticated()

.and()

.csrf().disable();

}

@Bean public BCryptPasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

}

}

```

鉴权各种情况处理类创建一个名为 `Authentications.java` 的类,用于处理鉴权相关逻辑:

```java@Servicepublic class Authentications {

@Autowired private RedisTemplate redisTemplate;

public boolean authenticate(String username, String password) {

// 从Redis中获取用户信息 String userInfo = redisTemplate.opsForValue().get(username);

if (userInfo == null || !passwordEncoder.matches(password, userInfo)) {

return false;

}

return true;

}

@Autowired private PasswordEncoder passwordEncoder;

public String generateToken(String username) {

//生成JWT token String token = Jwts.builder()

.setSubject(username)

.setExpiration(new Date(System.currentTimeMillis() +30 *60 *1000))

.signWith(SignatureAlgorithm.HS512, passwordEncoder.encode("secret"))

.compact();

return token;

}

}

```

无权访问用户创建一个名为 `NoAuthorityUser.java` 的类,用于表示无权访问的用户:

```javapublic class NoAuthorityUser implements User {

@Override public Collection getAuthorities() {

return Collections.emptyList();

}

@Override public String getPassword() {

return null;

}

@Override public String getUsername() {

return "no-authority-user";

}

}

```

未授权访问用户创建一个名为 `UnauthorizedUser.java` 的类,用于表示未授权访问的用户:

```javapublic class UnauthorizedUser implements User {

@Override public Collection getAuthorities() {

return Collections.emptyList();

}

@Override public String getPassword() {

return null;

}

@Override public String getUsername() {

return "unauthorized-user";

}

}

```

Token权限鉴定 Token过滤器创建一个名为 `TokenFilter.java` 的类,用于过滤 Token:

```java@Componentpublic class TokenFilter implements Filter {

@Autowired private Authentications authentications;

@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest = (HttpServletRequest) request;

String token = if (token != null && !token.isEmpty()) {

try {

Jws claims = Jwts.parser().setSigningKey(authentications.passwordEncoder.encode("secret")).parseClaimsJws(token);

String username = claims.getBody().getSubject();

User user = authentications.userDetailsService.loadUserByUsername(username);

if (user != null) {

user);

}

} catch (Exception e) {

// Token 验证失败 }

}

chain.doFilter(request, response);

}

}

```

Token过滤器配置在 `SecurityConfig.java` 中添加 Token 过滤器:

```java@Overrideprotected void configure(HttpSecurity throws Exception {

.antMatchers("/login").permitAll()

.anyRequest().authenticated()

.and()

.csrf().disable();

TokenFilter(), AnyRequestFilter.class);

}

```

Redis缓存 RedisTemplate配置在 `application.yml` 中添加 Redis Template 配置:

```ymlspring:

redis:

host: localhost port:6379 password: your-redis-password```

RedisTemplate使用在 `Authentications.java` 中使用 Redis Template:

```java@Autowiredprivate RedisTemplate redisTemplate;

public boolean authenticate(String username, String password) {

// 从Redis中获取用户信息 String userInfo = redisTemplate.opsForValue().get(username);

if (userInfo == null || !passwordEncoder.matches(password, userInfo)) {

return false;

}

return true;

}

```

小程序登录 小程序登录接口创建一个名为 `LoginController.java` 的类,用于处理小程序登录:

```java@RestController@RequestMapping("/login")

public class LoginController {

@Autowired private Authentications authentications;

@PostMapping public String login(@RequestBody LoginRequest request) {

// 验证用户信息 boolean isValid = authentications.authenticate(request.getUsername(), request.getPassword());

if (isValid) {

//生成JWT token String token = authentications.generateToken(request.getUsername());

return token;

} else {

return "invalid username or password";

}

}

}

```

小程序登录请求创建一个名为 `LoginRequest.java` 的类,用于表示小程序登录请求:

```javapublic class LoginRequest {

private String username;

private String password;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

}

```

Token权限鉴定 Token过滤器配置在 `SecurityConfig.java` 中添加 Token 过滤器:

```java@Overrideprotected void configure(HttpSecurity throws Exception {

.antMatchers("/login").permitAll()

.anyRequest().authenticated()

.and()

.csrf().disable();

TokenFilter(), AnyRequestFilter.class);

}

```

Redis缓存 RedisTemplate配置在 `application.yml` 中添加 Redis Template 配置:

```ymlspring:

redis:

host: localhost port:6379 password: your-redis-password```

RedisTemplate使用在 `Authentications.java` 中使用 Redis Template:

```java@Autowiredprivate RedisTemplate redisTemplate;

public boolean authenticate(String username, String password) {

// 从Redis中获取用户信息 String userInfo = redisTemplate.opsForValue().get(username);

if (userInfo == null || !passwordEncoder.matches(password, userInfo)) {

return false;

}

return true;

}

```

小程序登录 小程序登录接口创建一个名为 `LoginController.java` 的类,用于处理小程序登录:

```java@RestController@RequestMapping("/login")

public class LoginController {

@Autowired private Authentications authentications;

@PostMapping public String login(@RequestBody LoginRequest request) {

// 验证用户信息 boolean isValid = authentications.authenticate(request.getUsername(), request.getPassword());

if (isValid) {

//生成JWT token String token = authentications.generateToken(request.getUsername());

return token;

} else {

return "invalid username or password";

}

}

}

```

小程序登录请求创建一个名为 `LoginRequest.java` 的类,用于表示小程序登录请求:

```javapublic class

小程序登录springbootspringSecurityredis微信小程序jwt

版权声明:除非特别标注,否则均为网络文章,侵权请联系站长删除。

上一篇 仿微信语音接听黑屏亮屏

下一篇 微信二维码扫描下载APK