前端实现免密登录

本文介绍了如何在Vue路由守卫中处理URL参数中的加密token,实现用户无需登录即可通过验证直接访问首页,涉及Base64解码、token有效性检查和用户信息存储的过程。
摘要由CSDN通过智能技术生成

最近接到个需求,就是实现免密登录,用户在url参数中携带加密的token,直接进入首页,不需要登录,具体实现如下:

在router.beforeEach守卫中进行处理

router.beforeEach(async (to: any, from, next) => {
  const token = to.query.token // 从路由参数中获取 token
  //判断url是否携带token
  if (to.meta.whiteList && token) {
    const decodedToken = Base64.decode(token);// 解密 Base64 编码的 token
    //验证 token 的有效性并登录用户 
    let data = {
      token: decodedToken
    }
    try {
      let res:any = await checktoken(data)
        // .then((res: any) => {
        // 验证成功,将用户信息保存到全局状态管理或本地存储 pinia
      if (res.code == 0) {
          
          storage.local.set('token', res.data.accessToken);
          // storage.local.set('token', Base64.decode(token));
          storage.local.set('username', res.data.userName)
          storage.local.set('expiresTime', res.data.expiresTime)
          storage.local.set('tenantid', JSON.stringify(res.data.tenantId))
          let asTenant = ref({
            id: res.data.tenantId,
            name: res.data.tenantName
          })

          storage.local.set('asTenant', JSON.stringify(asTenant.value))
          userStore.token = res.data.accessToken
          userStore.username = res.data.userName
          userStore.expiresTime = res.data.expiresTime
          userStore.tenantid = res.data.tenantId
          userStore.asTenant = asTenant.value
          //修改登录状态
          userStore.isLogin = true
          // console.log(userStore.isLogin);

        } 
      // })
  }
     catch (error) {
      // console.log(error, '222');
      userStore.urltoken = true
    }
     
  }

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
实现前端免密登录,可以使用 OAuth2 协议和 Spring Cloud Security 来完成。下面是一个简单的实现步骤: 1. 前端应用向认证服务器发起授权请求,请求的参数包括 client_id、response_type、redirect_uri 等。 2. 认证服务器返回授权页面,用户在该页面输入用户名和密码进行登录。 3. 用户登录成功后,认证服务器会将 access_token 和 refresh_token 返回给前端应用。 4. 前端应用将 access_token 存储在客户端的 localStorage 中。 5. 前端应用每次向后端服务发起请求时,将 access_token 附加在请求头中,后端服务通过 access_token 来判断用户是否已经登录。 下面是一个简单的示例代码: 前端代码: ```javascript // 登录 function login(username, password) { var params = { grant_type: 'password', client_id: 'your_client_id', username: username, password: password }; axios.post('/oauth/token', params).then(function(res) { localStorage.setItem('access_token', res.data.access_token); }); } // 请求数据 function fetchData() { var token = localStorage.getItem('access_token'); axios.get('/api/data', { headers: { 'Authorization': 'Bearer ' + token } }).then(function(res) { console.log(res.data); }); } ``` 后端代码: ```java @Configuration @EnableWebSecurity @EnableAuthorizationServer public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public TokenStore tokenStore() { return new InMemoryTokenStore(); } @Bean public JwtAccessTokenConverter accessTokenConverter() { return new JwtAccessTokenConverter(); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore()) .accessTokenConverter(accessTokenConverter()); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("your_client_id").secret("your_secret") .authorizedGrantTypes("password", "refresh_token").scopes("read", "write"); } } ``` 以上代码仅供参考,实际开发中需要根据具体业务场景进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值