国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Boot + Vue的網(wǎng)上商城之springsecurity+jwt+redis實現(xiàn)用戶權(quán)限認證實現(xiàn)

這篇具有很好參考價值的文章主要介紹了Spring Boot + Vue的網(wǎng)上商城之springsecurity+jwt+redis實現(xiàn)用戶權(quán)限認證實現(xiàn)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Spring Boot + Vue的網(wǎng)上商城之springsecurity+jwt+redis實現(xiàn)用戶權(quán)限認證實現(xiàn)

在網(wǎng)上商城項目中,用戶的安全性是非常重要的。為了實現(xiàn)用戶權(quán)限認證和安全校驗,我們可以使用Spring Security、JWT和Redis來實現(xiàn)。本篇博客將詳細介紹后端和前臺的實現(xiàn)過程,并提供相應(yīng)的代碼案例。

思路

當(dāng)用戶點擊登錄按鈕時,前端發(fā)送一個POST請求到后端的登錄接口,傳遞用戶名和密碼。后端接收到請求后,驗證用戶名和密碼的正確性。如果驗證通過,后端生成一個JWT(JSON Web Token),并將其返回給前端。

前端接收到JWT后,將其存儲在本地,例如使用localStorage。然后通過Vue Router進行頁面跳轉(zhuǎn),跳轉(zhuǎn)到需要進行權(quán)限校驗的頁面。

在需要進行權(quán)限校驗的頁面組件中,可以在created鉤子函數(shù)中檢查本地存儲中是否存在JWT。如果不存在,則表示用戶未登錄或登錄已過期,可以通過Vue Router跳轉(zhuǎn)到登錄頁面。

需要注意的是,在每次向后端發(fā)送請求時,需要將JWT作為請求頭的Authorization字段進行傳遞,以便后端進行權(quán)限校驗。

后端在接收到請求時,可以通過解析JWT來驗證用戶的身份和權(quán)限。JWT中通常包含用戶ID、用戶名、權(quán)限信息等。后端可以使用Spring Security的相關(guān)功能進行JWT的解析和校驗。

總結(jié)來說,用戶登錄和權(quán)限認證的流程可以簡化為以下幾個步驟:

  1. 用戶在前端頁面輸入用戶名和密碼,并點擊登錄按鈕。
  2. 前端發(fā)送POST請求到后端的登錄接口,傳遞用戶名和密碼。
  3. 后端驗證用戶名和密碼的正確性,如果驗證通過,生成JWT并返回給前端。
  4. 前端接收到JWT后,將其存儲在本地。
  5. 前端通過Vue Router進行頁面跳轉(zhuǎn),跳轉(zhuǎn)到需要進行權(quán)限校驗的頁面。
  6. 在需要進行權(quán)限校驗的頁面組件中,檢查本地存儲中是否存在JWT,如果不存在,則跳轉(zhuǎn)到登錄頁面。
  7. 在每次向后端發(fā)送請求時,將JWT作為請求頭的Authorization字段進行傳遞。
  8. 后端在接收到請求時,解析JWT并進行權(quán)限校驗,校驗通過則返回相應(yīng)的數(shù)據(jù)或頁面。

后端實現(xiàn)

Spring Security配置

首先,在后端的Spring Boot項目中,我們需要配置Spring Security來實現(xiàn)用戶權(quán)限認證。我們可以創(chuàng)建一個SecurityConfig類來配置Spring Security。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager(), userService))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

上述代碼中,我們配置了允許訪問/api/public/**路徑的請求,其他請求需要進行認證。我們還添加了兩個過濾器JwtAuthenticationFilterJwtAuthorizationFilter來處理JWT的認證和授權(quán)。

JWT認證和授權(quán)過濾器

接下來,我們來實現(xiàn)JWT的認證和授權(quán)過濾器。

public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        setFilterProcessesUrl("/api/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            UserCredentials credentials = new ObjectMapper().readValue(request.getInputStream(), UserCredentials.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                    credentials.getUsername(), credentials.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String token = Jwts.builder()
                .setSubject(((User) authResult.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET)
                .compact();
        response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
    }
}
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    private UserService userService;

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserService userService) {
        super(authenticationManager);
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(SecurityConstants.HEADER_STRING);
        if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(SecurityConstants.HEADER_STRING);
        if (token != null) {
            String username = Jwts.parser()
                    .setSigningKey(SecurityConstants.SECRET)
                    .parseClaimsJws(token.replace(SecurityConstants.TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();
            if (username != null) {
                User user = userService.loadUserByUsername(username);
                return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            }
            return null;
        }
        return null;
    }
}

上述代碼中,JwtAuthenticationFilter處理登錄請求,將用戶的認證信息封裝為JWT,并添加到響應(yīng)頭中。JwtAuthorizationFilter處理其他請求,從請求頭中獲取JWT并進行認證和授權(quán)。

用戶服務(wù)和認證

為了實現(xiàn)用戶的認證和授權(quán),我們需要創(chuàng)建一個用戶服務(wù)實現(xiàn)類UserService。

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        return user;
    }
}

上述代碼中,我們通過用戶名從數(shù)據(jù)庫中獲取用戶信息。

Redis存儲Token

為了增加用戶登錄的安全性,我們可以將JWT存儲到Redis中,并設(shè)置過期時間。

@Service
public class TokenService {

    private RedisTemplate<String, Object> redisTemplate;

    public TokenService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void saveToken(String username, String token) {
        redisTemplate.opsForValue().set(username, token, SecurityConstants.EXPIRATION_TIME, TimeUnit.MILLISECONDS);
    }

    public boolean validateToken(String username, String token) {
        String storedToken = (String) redisTemplate.opsForValue().get(username);
        return storedToken != null && storedToken.equals(token);
    }

    public void deleteToken(String username) {
        redisTemplate.delete(username);
    }
}

上述代碼中,我們使用redisTemplate將用戶名和JWT存儲到Redis中,并設(shè)置過期時間。在校驗Token時,我們從Redis中獲取存儲的Token進行比較。

前臺實現(xiàn)

在前臺,我們使用Vue來實現(xiàn)用戶登錄和權(quán)限認證的功能。我們需要創(chuàng)建相應(yīng)的組件和路由來實現(xiàn)用戶登錄和權(quán)限校驗。

登錄組件

<template>
  <div>
    <h1>用戶登錄</h1>
    <form @submit.prevent="login">
      <label for="username">用戶名:</label>
      <input type="text" id="username" v-model="username" required>
      <br>
      <label for="password">密碼:</label>
      <input type="password" id="password" v-model="password" required>
      <br>
      <button type="submit">登錄</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    login() {
      // 調(diào)用后端API接口進行用戶登錄
      // 使用axios或其他HTTP庫發(fā)送POST請求
    }
  }
};
</script>

路由配置

import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from './components/Login.vue';
import ProductList from './components/ProductList.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/login', component: Login },
  { path: '/products', component: ProductList, meta: { requiresAuth: true } }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;

在上述代碼中,我們配置了兩個路由,/login用于用戶登錄,/products用于展示商品列表。在/products路由中,我們設(shè)置了requiresAuthtrue,表示需要進行權(quán)限校驗。在路由導(dǎo)航守衛(wèi)中,我們檢查是否存在Token,如果不存在則跳轉(zhuǎn)到登錄頁面。

入口文件

import Vue from 'vue';
import App from './App.vue';
import router from './router';

new Vue({el: '#app',
  router,
  render: h => h(App)
}).$mount('#app');

在入口文件中,我們創(chuàng)建了一個Vue實例,并將路由配置和根組件傳入。然后將Vue實例掛載到#app元素上。

用戶登錄

在登錄組件中,我們需要調(diào)用后端API接口進行用戶登錄,并將返回的Token保存到本地存儲中。

methods: {
  login() {
    axios.post('/api/login', {
      username: this.username,
      password: this.password
    })
    .then(response => {
      const token = response.data.token;
      localStorage.setItem('token', token);
      this.$router.push('/products');
    })
    .catch(error => {
      console.error(error);
    });
  }
}

在上述代碼中,我們使用axios庫發(fā)送POST請求到后端的登錄接口。如果登錄成功,會返回一個包含Token的響應(yīng)。我們將Token保存到本地存儲中,并使用$router.push方法跳轉(zhuǎn)到商品列表頁面。

權(quán)限校驗

在商品列表組件中,我們需要進行權(quán)限校驗,只有在用戶登錄成功并且存在Token的情況下才能訪問該頁面。

export default {
  created() {
    if (!localStorage.getItem('token')) {
      this.$router.push('/login');
    }
  }
};

在上述代碼中,我們在組件創(chuàng)建時檢查本地存儲中是否存在Token,如果不存在則跳轉(zhuǎn)到登錄頁面。

總結(jié)

本文介紹了如何使用Spring Security和Vue實現(xiàn)用戶登錄和權(quán)限認證的功能。通過使用JWT和Redis存儲Token,我們可以實現(xiàn)無狀態(tài)的用戶認證,提高系統(tǒng)的可擴展性和安全性。同時,通過使用Vue的路由導(dǎo)航守衛(wèi),我們可以實現(xiàn)前端的權(quán)限校驗,確保只有登錄用戶才能訪問受限資源。希望本文能對你理解和實現(xiàn)用戶登錄和權(quán)限認證功能有所幫助。文章來源地址http://www.zghlxwxcb.cn/news/detail-733538.html

到了這里,關(guān)于Spring Boot + Vue的網(wǎng)上商城之springsecurity+jwt+redis實現(xiàn)用戶權(quán)限認證實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Spring Boot + Vue + Element UI的網(wǎng)上商城后臺管理之訂單管理系統(tǒng)

    以下是訂單管理系統(tǒng)的思維導(dǎo)圖,展示了系統(tǒng)的主要功能和模塊之間的關(guān)系。 根節(jié)點 訂單列表 查看訂單列表 搜索訂單 排序訂單 導(dǎo)出訂單列表 訂單詳情 查看訂單詳情 修改訂單信息 修改商品信息 修改價格 修改收貨地址 取消訂單 處理訂單 處理訂單操作 確認訂單 拒絕訂單

    2024年02月03日
    瀏覽(40)
  • 【java畢業(yè)設(shè)計】基于Spring Boot+mysql的網(wǎng)上商城購物系統(tǒng)設(shè)計與實現(xiàn)(程序源碼)-網(wǎng)上商城購物系統(tǒng)

    【java畢業(yè)設(shè)計】基于Spring Boot+mysql的網(wǎng)上商城購物系統(tǒng)設(shè)計與實現(xiàn)(程序源碼)-網(wǎng)上商城購物系統(tǒng)

    大家好,今天給大家介紹基于Spring Boot+mysql的網(wǎng)上商城購物系統(tǒng)設(shè)計與實現(xiàn),本論文只截取部分文章重點,文章末尾附有本畢業(yè)設(shè)計完整源碼及論文的獲取方式。更多畢業(yè)設(shè)計源碼可訂閱查看上方【畢業(yè)設(shè)計】專欄獲取哦。 隨著科學(xué)技術(shù)的飛速發(fā)展,社會的方方面面、各行各

    2024年02月06日
    瀏覽(22)
  • 網(wǎng)上購物系統(tǒng)的設(shè)計與實現(xiàn)/在線商城/基于spring boot的電商平臺/基于Java的商品銷售系統(tǒng)

    網(wǎng)上購物系統(tǒng)的設(shè)計與實現(xiàn)/在線商城/基于spring boot的電商平臺/基于Java的商品銷售系統(tǒng)

    ? 摘 ??要 本畢業(yè)設(shè)計的內(nèi)容是設(shè)計并且實現(xiàn)一個基于 Springboot 的 網(wǎng)上購物系統(tǒng) 。它是在Windows下,以MYSQL為數(shù)據(jù)庫開發(fā)平臺,Tomcat網(wǎng)絡(luò)信息服務(wù)作為應(yīng)用服務(wù)器。 網(wǎng)上購物系統(tǒng) 的功能已基本實現(xiàn),主要包括用戶管理、數(shù)碼分類管理、數(shù)碼產(chǎn)品管理、服裝分類管理、服裝管理

    2024年02月12日
    瀏覽(26)
  • 基于Springboot+vue的網(wǎng)上商城購物系統(tǒng)設(shè)計與實現(xiàn)

    基于Springboot+vue的網(wǎng)上商城購物系統(tǒng)設(shè)計與實現(xiàn)

    ?博主介紹 :?? 大家好,我是一名在Java圈混跡十余年的程序員,精通Java編程語言,同時也熟練掌握微信小程序、Python和Android等技術(shù),能夠為大家提供全方位的技術(shù)支持和交流。 我擅長在JavaWeb、SSH、SSM、SpringBoot等框架下進行項目開發(fā),具有豐富的項目經(jīng)驗和開發(fā)技能。我

    2024年02月10日
    瀏覽(20)
  • vue+django+python辦公耗材網(wǎng)上商城采購庫存管理系統(tǒng)

    vue+django+python辦公耗材網(wǎng)上商城采購庫存管理系統(tǒng)

    辦公耗材采購信息管理是信息行業(yè)業(yè)務(wù)流程過程中十分重要且必備的環(huán)節(jié)之一,在信息行業(yè)業(yè)務(wù)流程當(dāng)中起著承上啟下的作用,其重要性不言而喻。但是,目前許多信息行業(yè)在具體的業(yè)務(wù)流程處理過程中仍然使用手工操作的方式來實施,不僅費時、費力,效率低下,而且無法

    2024年02月21日
    瀏覽(23)
  • 畢設(shè)分享springBoot+vue 網(wǎng)上購物商城系統(tǒng)(含源碼+論文)

    畢設(shè)分享springBoot+vue 網(wǎng)上購物商城系統(tǒng)(含源碼+論文)

    Hi,各位同學(xué)好呀,這里是M學(xué)姐! 今天向大家分享一個今年(2022)最新完成的畢業(yè)設(shè)計項目作品,【基于SSM的網(wǎng)上購物商城】 學(xué)姐根據(jù)實現(xiàn)的難度和等級對項目進行評分(最低0分,滿分5分) 難度系數(shù):3分 工作量:5分 創(chuàng)新點:3分 界面美化:5分 界面美化的補充說明:使用vue的

    2024年02月11日
    瀏覽(26)
  • java+vue畢業(yè)設(shè)計項目 網(wǎng)上購物商城系統(tǒng)(含源碼+論文)

    java+vue畢業(yè)設(shè)計項目 網(wǎng)上購物商城系統(tǒng)(含源碼+論文)

    Hi,各位同學(xué)好呀,這里是M學(xué)姐! 今天向大家分享一個今年(2022)最新完成的畢業(yè)設(shè)計項目作品,【基于SSM的網(wǎng)上購物商城】 學(xué)姐根據(jù)實現(xiàn)的難度和等級對項目進行評分(最低0分,滿分5分) 難度系數(shù):3分 工作量:5分 創(chuàng)新點:3分 界面美化:5分 界面美化的補充說明:使用vue的

    2024年02月03日
    瀏覽(20)
  • 基于JavaWeb+SSM+Vue基于微信小程序的網(wǎng)上商城系統(tǒng)的設(shè)計和實現(xiàn)

    基于JavaWeb+SSM+Vue基于微信小程序的網(wǎng)上商城系統(tǒng)的設(shè)計和實現(xiàn)

    目錄 1系統(tǒng)概述 1 1.1 研究背景 1 1.2研究目的 1 1.3系統(tǒng)設(shè)計思想 1 2相關(guān)技術(shù) 2 2.1微信小程序 2 2.2 MYSQL數(shù)據(jù)庫 3 2.3 uni-app 3 2.4 SSM框架簡介 4 3系統(tǒng)分析 5 3.1可行性分析 5 3.1.1技術(shù)可行性 6 3.1.2經(jīng)濟可行性 6 3.1.3操作可行性 6 3.2系統(tǒng)性能分析 6 3.2.1 系統(tǒng)安全性 6 3.2.2 數(shù)據(jù)完整性 7 3.3系

    2024年01月21日
    瀏覽(31)
  • 基于小程序的網(wǎng)上商城設(shè)計+springboot+vue.js附帶文章和源代碼設(shè)計說明文檔ppt

    基于小程序的網(wǎng)上商城設(shè)計+springboot+vue.js附帶文章和源代碼設(shè)計說明文檔ppt

    ?? 博主介紹 :?CSDN特邀作者、985計算機專業(yè)畢業(yè)、某互聯(lián)網(wǎng)大廠高級全棧開發(fā)程序員、碼云/掘金/華為云/阿里云/InfoQ/StackOverflow/github等平臺優(yōu)質(zhì)作者、專注于Java、小程序、前端、python等技術(shù)領(lǐng)域和畢業(yè)項目實戰(zhàn),以及程序定制化開發(fā)、全棧講解、就業(yè)輔導(dǎo)、面試輔導(dǎo)、簡

    2024年02月20日
    瀏覽(23)
  • springboot網(wǎng)上商城項目(一)

    springboot網(wǎng)上商城項目(一)

    ????靜態(tài)資源及sql文件 鏈接:https://pan.baidu.com/s/1X-yjmQcPD3PqS21x0HplNA?pwd=23gr 提取碼:23gr 1.項目分析 ?????項目功能:登錄,注冊,熱銷商品,用戶管理(密碼,個人信息,頭像,收貨地址),購物車(展示,增加,刪除),訂單模塊 ?????開發(fā)順序:注冊,登錄,用戶管理,購物車,商品,訂單模塊

    2024年02月03日
    瀏覽(17)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包