springboot+jwt做登录鉴权(附完整代码)

本文介绍了如何使用JWT进行登录鉴权,包括编写JWT工具类以生成和验证token,以及在登录接口中如何调用这些工具类为前端返回token。详细阐述了每个步骤的实现思路,并提供了相关代码片段。
摘要由CSDN通过智能技术生成


前言

提示:这里可以添加本文要记录的大概内容:


一、jwt做登录鉴权

1.1 写出jwt 生成token 的工具类

1.1.1 编写获取token工具类方法(getToken() )

思路:
一、首先考虑要接收的参数。要知道用户的ID或者用户名、角色等。因此这里把这三个属性封装到一个AuthInfo对象中。还要传入过期时间 和加密字符串信息。

@Data
public class AuthInfo {
   
    private Long UserId;
    private String userName;
    private String roles;
}
public static String getToken(AuthInfo authInfo, Date expireDate, String secret){
   
return "";
}

二、 进入方法时,首先判断参数是否为空,这里我们可以使用谷歌的包:com.google.common.base.Preconditions;里面有对应的API可以非常方便的做验证。
代码:

//做验证
        Preconditions.checkArgument(authInfo != null,"加密内容不能为null");
        Preconditions.checkArgument(expireDate != null,"过期时间异常");
        Preconditions.checkArgument(secret != null,"加密密码不能为null");

三、使用JWT的Api调用方法,将Header和签名等参数赋值。

Map<String, Object> map = new HashMap<>();
// 固定格式
       map.put("alg", "HS256");
       map.put("typ", "JWT");

       String token = null;//签名
       try {
   
           token = JWT.create()
                   .withHeader(map)//头
                   // 参数
                   .withClaim(USER_ID,authInfo.getUserId())
                   .withClaim(USER_NAME,authInfo.getUserName())
                   .withClaim(USER_ROLES,authInfo.getRoles())
                   .withIssuedAt(new Date())//签名时间
                   .withExpiresAt(expireDate)//过期时间
                   .sign(Algorithm.HMAC256(secret));
       } catch (IllegalArgumentException e) {
   
           e.printStackTrace();
       } catch (JWTCreationException e) {
   
           e.printStackTrace();
       }

四、返回token 字符串,下面是完整代码:

package com.tzw.gene.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.google.common.base.Preconditions;
import com.tzw.gene.auth.AuthInfo;
import java.util.Date;
import java.util.HashMap
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
为了实现SpringBoot+Vue前后端分离的登录界面使用JWT鉴权,需要进行以下步骤: 1.在SpringBoot中配置SpringSecurity,包括用户认证和授权,可以参考引用中的实现方式。 2.在SpringBoot中配置JWT,包括生成Token和解析Token,可以使用jjwt库实现,可以参考引用中的maven依赖配置。 3.在Vue中实现登录界面,包括输入用户名和密码,发送POST请求到后端验证用户信息,并获取Token。 4.在Vue中使用获取到的Token进行后续请求的鉴权,可以在请求头中添加Authorization字段,值为Bearer加上Token。 下面是一个简单的示例代码,仅供参考: 1. SpringBoot中的配置 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/auth/**") .permitAll() .anyRequest() .authenticated(); // Add our custom JWT security filter http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } } ``` 2. Vue中的登录界面 ```html <template> <div> <h2>Login</h2> <form @submit.prevent="login"> <div> <label>Username:</label> <input type="text" v-model="username" required> </div> <div> <label>Password:</label> <input type="password" v-model="password" required> </div> <button type="submit">Login</button> </form> </div> </template> <script> import axios from 'axios'; export default { data() { return { username: '', password: '' }; }, methods: { async login() { try { const response = await axios.post('/api/auth/login', { username: this.username, password: this.password }); const token = response.data.token; localStorage.setItem('token', token); axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; this.$router.push('/'); } catch (error) { console.error(error); } } } }; </script> ``` 3. Vue中的请求鉴权 ```javascript import axios from 'axios'; const token = localStorage.getItem('token'); if (token) { axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; } axios.get('/api/protected/resource') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值