マイクロサービス非ログインサービスの春のセッション+春のセキュリティプラクティス

構成

Springセッションをまだ使用していないときは、バックエンドでセッションを永続性レイヤー(redisなど)にアクティブに保存する方法を理解していません。最近のSpringセッションのドキュメントとブログを読んだ後、理解しました。簡単に言えば、それは次のAパッセージです:

Spring Sessionは、Filterを実装するspringSessionRepositoryFilterという名前のSpringBeanを作成します。フィルタは、SpringSessionによってサポートされるHttpSession実装の置き換えを担当します。

ただし、spring.ioの公式Webサイトにある構成チュートリアルは、実際には良くありません。構成時にredisにデータを挿入することは不可能であり、指定されたデモをこのマシンで実行することはできません。
今私の構成スキームを与える

頼る

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

application.properties

# 必须要加,否则你加依赖不加这个连启动都报错
spring.session.store-type=redis
# 默认为localhost:6379,可以通过配置更改
spring.redis.host=localhost
# Redis server password
# 如果密码为空,就不要写了,否则也报错
# spring.redis.password=
# Redis server port.
spring.redis.port=6379
# 指定储存的位置
spring.session.redis.namespace=redis:session
spring.session.redis.flush-mode=immediate
spring.session.timeout=5m
# 超时断连,不指定可能会报unable to connect to redis
spring.redis.timeout=3000

redisを表示

リクエストを送信し、redisのキー*を確認すると、保存されたセッションが表示されます
ここに画像の説明を挿入

春のセキュリティを構成する

ログイン以外の側として、セキュリティ構成を複雑にする必要はなく、単純なsecurityConfigクラスのみが必要です。

依存関係を導入する

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

SecurityConfigクラス

package com.ilife.weiboservice.config;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }
}

コントローラ

インターフェースを保護するには、@ PreAuthorizeに次のように注釈を付ける必要があります

    @ApiOperation(notes = "Get all Weibos from database of one user specified by userID", value = "get one user's Weibos", httpMethod = "GET")
    @RequestMapping(path = "/weibo/getWeibos")
    @PreAuthorize("hasRole('ROLE_USER')")
    public List<Weibo> getWeibos(@ApiParam(name = "userId", value = "The user ID of a WeiBo user,should be a Long Integer") @RequestParam("userId") Long uid) {
    
    
        System.out.println("********** getWeibos **********");
        return weiboService.findAllByUid(uid);
    }

おすすめ

転載: blog.csdn.net/weixin_44602409/article/details/107556289