最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringSecurity的TokenStore四種實現(xiàn)方式小結

 更新時間:2024年01月30日 09:50:56   作者:Javaesandyou  
本文主要介紹了SpringSecurity的TokenStore四種實現(xiàn)方式小結,分別是InMemoryTokenStore,JdbcTokenStore,JwkTokenStore,RedisTokenStore,具有一定的參考價值,感興趣的可以了解一下

什么是Token Store

在Web開發(fā)中,Token Store 通常用于存儲用戶身份驗證令牌(Tokens),例如 JSON Web Tokens (JWT) 或其他形式的令牌。這些令牌可以用于驗證用戶身份,實現(xiàn)用戶會話管理以及訪問控制。

一種簡單的Token Store示例,使用Node.js和Express框架以及一個基于內(nèi)存的Token存儲方式:

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

// In-memory Token Store
const tokenStore = {};

// Secret key for JWT (replace with a strong, secret key in production)
const secretKey = 'your_secret_key';

// Middleware to verify JWT
function verifyToken(req, res, next) {
    const token = req.headers.authorization;

    if (!token) {
        return res.status(403).json({ message: 'No token provided' });
    }

    jwt.verify(token, secretKey, (err, decoded) => {
        if (err) {
            return res.status(401).json({ message: 'Failed to authenticate token' });
        }

        req.user = decoded;
        next();
    });
}

// Endpoint to generate and return a JWT
app.post('/login', (req, res) => {
    const { username, password } = req.body;

    // Authenticate user (replace with your actual authentication logic)
    // For simplicity, assume any username and password combination is valid
    const user = { username, role: 'user' };

    // Generate a JWT
    const token = jwt.sign(user, secretKey, { expiresIn: '1h' });

    // Store the token in memory
    tokenStore[token] = user;

    res.json({ token });
});

// Protected endpoint that requires a valid JWT for access
app.get('/protected', verifyToken, (req, res) => {
    res.json({ message: 'This is a protected endpoint', user: req.user });
});

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

 Spring Security 提供了幾個常見的 TokenStore 實現(xiàn),包括內(nèi)存中存儲、JDBC 數(shù)據(jù)庫存儲和基于 JWT(JSON Web Token)的存儲。下面將分別介紹這三種實現(xiàn)方式,并提供基本的代碼示例。

1. 內(nèi)存中存儲(In-Memory) 

這個是OAuth2默認采用的實現(xiàn)方式。在單服務上可以體現(xiàn)出很好特效(即并發(fā)量不大,并且它在失敗的時候不會進行備份),大多項目都可以采用此方法。根據(jù)名字就知道了,是存儲在內(nèi)存中,畢竟存在內(nèi)存,而不是磁盤中,調(diào)試簡易。但是,實際中很少使用,因為沒有持久化,會導致數(shù)據(jù)丟失。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public TokenStore inMemoryTokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
            .withClient("client")
            .secret("{noop}secret")  // 使用 "{noop}" 表示不加密
            .authorizedGrantTypes("password", "authorization_code", "refresh_token")
            .scopes("read", "write")
            .accessTokenValiditySeconds(3600)
            .refreshTokenValiditySeconds(86400);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .tokenStore(inMemoryTokenStore())
            .authenticationManager(authenticationManager);
    }
}

2. JDBC 數(shù)據(jù)庫存儲

這個是基于JDBC的實現(xiàn),令牌(Access Token)會保存到數(shù)據(jù)庫。這個方式,可以在多個服務之間實現(xiàn)令牌共享。因為是保存到數(shù)據(jù)庫,而且是必須有OAuth2默認的表結構:oauth_access_token。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private DataSource dataSource;

    @Bean
    public TokenStore jdbcTokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .tokenStore(jdbcTokenStore())
            .authenticationManager(authenticationManager);
    }
}

3. 基于 JWT 的存儲

jwt全稱 JSON Web Token。這個實現(xiàn)方式不用管如何進行存儲(內(nèi)存或磁盤),因為它可以把相關信息數(shù)據(jù)編碼存放在令牌里。JwtTokenStore 不會保存任何數(shù)據(jù),但是它在轉(zhuǎn)換令牌值以及授權信息方面與 DefaultTokenServices 所扮演的角色是一樣的。

既然jwt是將信息存放在令牌中,那么就得考慮其安全性,因此,OAuth2提供了JwtAccessTokenConverter實現(xiàn),添加jwtSigningKey,以此生成秘鑰,以此進行簽名,只有jwtSigningKey才能獲取信息。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Value("${security.jwt.client-id}")
    private String clientId;

    @Value("${security.jwt.client-secret}")
    private String clientSecret;

    @Value("${security.jwt.grant-type}")
    private String grantType;

    @Value("${security.jwt.scope-read}")
    private String scopeRead;

    @Value("${security.jwt.scope-write}")
    private String scopeWrite;

    @Value("${security.jwt.resource-ids}")
    private String resourceIds;

    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("secret");
        return converter;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory()
            .withClient(clientId)
            .secret("{noop}" + clientSecret)
            .authorizedGrantTypes(grantType)
            .scopes(scopeRead, scopeWrite)
            .resourceIds(resourceIds);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .tokenStore(jwtTokenStore())
            .accessTokenConverter(jwtAccessTokenConverter())
            .authenticationManager(authenticationManager);
    }
}

4.RedisTokenStore

顧名思義,就是講令牌信息存儲到redis中。首先必須保證redis連接正常。

@Autowired
private RedisConnectionFactory redisConnectionFactory;
/**
 * redis token 配置
 */
@Bean
public TokenStore redisTokenStore() {
    return new RedisTokenStore(redisConnectionFactory);
}


@Autowired(required = false)
private TokenStore redisTokenStore;
/**
 * 端點(處理入口)
 */
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
   endpoints.tokenStore(redisTokenStore);
   ....
}

小結

我們介紹了Spring Security中四種不同的Token Store實現(xiàn)方式。具體包括內(nèi)存中存儲、JDBC數(shù)據(jù)庫存儲、保存到redis和基于JWT的存儲。每個實現(xiàn)方式都涉及到授權服務器的配置,用于管理和驗證令牌,以及客戶端詳情的配置。

到此這篇關于SpringSecurity的TokenStore四種實現(xiàn)方式小結的文章就介紹到這了,更多相關SpringSecurity TokenStore內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • IDEA設置JVM運行參數(shù)的方法步驟

    IDEA設置JVM運行參數(shù)的方法步驟

    這篇文章主要介紹了IDEA設置JVM運行參數(shù)的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-08-08
  • PowerJob的OhMyClassLoader工作流程源碼解讀

    PowerJob的OhMyClassLoader工作流程源碼解讀

    這篇文章主要介紹了PowerJob的OhMyClassLoader工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Java實現(xiàn)根據(jù)圖片url下載圖片并動態(tài)添加水印

    Java實現(xiàn)根據(jù)圖片url下載圖片并動態(tài)添加水印

    這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)根據(jù)圖片url下載圖片并動態(tài)添加水印,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下
    2026-01-01
  • 一文搞懂Spring?Security異常處理機制

    一文搞懂Spring?Security異常處理機制

    這篇文章主要為大家詳細介紹一下Spring?Security異常處理機制,文中的示例代碼講解詳細,對我們學習Spring?Security有一定幫助,感興趣的可以學習一下
    2022-07-07
  • 解決java中的父類私有成員變量的繼承問題

    解決java中的父類私有成員變量的繼承問題

    這篇文章主要介紹了解決java中的父類私有成員變量的繼承問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • 一篇文章掌握Java?Thread的類及其常見方法

    一篇文章掌握Java?Thread的類及其常見方法

    Thread類用于操作線程,是所以涉及到線程操作(如并發(fā))的基礎。本文將通過代碼對Thread類的功能作用及其常見方法進行分析
    2022-03-03
  • Java中Stream流對多個字段進行排序的方法

    Java中Stream流對多個字段進行排序的方法

    我們在處理數(shù)據(jù)的時候經(jīng)常會需要進行排序后再返回給前端調(diào)用,比如按照時間升序排序,前端展示數(shù)據(jù)就是按時間先后進行排序,下面這篇文章主要給大家介紹了關于Java中Stream流對多個字段進行排序的相關資料,需要的朋友可以參考下
    2023-10-10
  • Java實現(xiàn)微信掃碼登入的實例代碼

    Java實現(xiàn)微信掃碼登入的實例代碼

    這篇文章主要介紹了java實現(xiàn)微信掃碼登入功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • MyBatis基于pagehelper實現(xiàn)分頁原理及代碼實例

    MyBatis基于pagehelper實現(xiàn)分頁原理及代碼實例

    這篇文章主要介紹了MyBatis基于pagehelper實現(xiàn)分頁原理及代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • Java中自己如何實現(xiàn)log2(N)

    Java中自己如何實現(xiàn)log2(N)

    這篇文章主要介紹了Java中自己實現(xiàn)log2(N)的方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08

最新評論

盐津县| 桐庐县| 西城区| 仁布县| 阜南县| 宕昌县| 陇南市| 温泉县| 南投县| 通许县| 济阳县| 济南市| 山阴县| 迁西县| 周至县| 务川| 惠安县| 吉安县| 平定县| 新乐市| 涞水县| 大新县| 鄱阳县| 随州市| 山东省| 色达县| 濉溪县| 通辽市| 河南省| 集安市| 云浮市| 泰州市| 法库县| 蕉岭县| 南康市| 合肥市| 阜平县| 徐汇区| 竹溪县| 黄骅市| 乐东|