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

spring security - 快速整合 springboot

這篇具有很好參考價值的文章主要介紹了spring security - 快速整合 springboot。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1.引入依賴

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.1</version>
        </dependency>


2.配置 application.properties

server.port=8086
#
spring.application.name=security-sample
spring.main.allow-bean-definition-overriding=true
spring.mvc.static-path-pattern=/static/**
# thymeleaf 配置
spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

# 數(shù)據(jù)庫配置
spring.datasource.name=defaultDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_plain?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root123
# 連接池配置
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=8
spring.datasource.hikari.minimum-idle=4
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.max-lifetime=50000
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.pool-name=HikariCP
# mybatis 配置
mybatis.mapper-locations=classpath:mappers/*xml
mybatis.type-aliases-package=com.sky.biz.entity
mybatis.configuration.map-underscore-to-camel-case=true


3.定制開發(fā) - 認證流程的 UserDetailsService

說明:UserDetailsService 負責(zé)在 Security 框架中從數(shù)據(jù)源中查詢出2大主要信息,
分別為:認證信息(賬號、密碼)、授權(quán)信息(角色列表、權(quán)限列表)。隨后將這些信息封裝為 UserDetails 對象返回
留作后續(xù)進行登錄認證以及權(quán)限判斷。

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermsService permsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        BizUser bizUser = userService.queryByUserName(username);
        // 用戶存在,查詢封裝用戶的"角色與權(quán)限"信息到 UserDetails中,通常自定義封裝對象,繼承 UserDetails的子類 User
        if(bizUser != null) {
            // 使用 authorityList 封裝角色權(quán)限信息
            List<GrantedAuthority> authorityList = new ArrayList<>();
            // 查詢當前用戶 - 角色信息
            List<Role> roleList = roleService.getRoleListByUserId(bizUser.getId());
            for (Role role : roleList) {
                authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));
            }
            // 查詢當前用戶 - 權(quán)限信息
            List<Perms> permsList = permsService.getPermsListByUserId(bizUser.getId());
            for (Perms perm : permsList) {
                authorityList.add(new SimpleGrantedAuthority(perm.getPermCode()));
            }
            return new SecurityUser(bizUser, authorityList);
        }

        return null;
    }

}

4.定義封裝安全信息的實體類:SecurityUser

public class SecurityUser extends User {

    private BizUser bizUser;

    public SecurityUser(BizUser user, Collection<? extends GrantedAuthority> authorities) {
        super(user.getUserName(), user.getPassword(), true,true, true, true, authorities);
        this.bizUser = user;
    }

    public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    // get && set
    public BizUser getBizUser() {
        return bizUser;
    }

    public void setBizUser(BizUser bizUser) {
        this.bizUser = bizUser;
    }
}

5.自定義密碼校驗的類:PasswordEncoder,這里自由發(fā)揮,根據(jù)各自公司安全需要自定義

主要就是重寫 encode(CharSequence rawPassword)  和  matches(CharSequence rawPassword, String encodedPassword) 方法
如果不想自定義就配置成spring-security提供的 BCryptPasswordEncoder 來處理密碼加密與校驗

6.配置Security

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 開啟方法級別的細粒度權(quán)限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    // 配置對 HTTP 請求的安全攔截處理
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/static/**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .and().csrf().disable()
                .formLogin().loginPage("/login").loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/main") 
                .failureUrl("/fail")  
                .permitAll();

        // "/login","/main"與"/fail",都是對應(yīng) html頁面訪問controller跳轉(zhuǎn)路徑
        // 用戶權(quán)限不夠,處理并返回響應(yīng)
        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

                String header = request.getHeader("X-Requested-With");

                if("XMLHttpRequest".equals(header)) {
                    response.getWriter().print("403"); // 返回ajax 請求對應(yīng)的 json格式
                } else {
                    request.getRequestDispatcher("/error403").forward(request, response);
                }
            }
        });

    }


    @Bean
    public MyPasswordEncoder passwordEncoder() {
        return new MyPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(new passwordEncoder());
        // 或者:auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

    }
}


7.使用加密時:
    @Autowired
    private MyPasswordEncoder passwordEncoder;

    // 方法1:
    String encodePwd = passwordEncoder.encode(user.getPassword());
    // 方法2:
    String encodePwd = new BCryptPasswordEncoder().encode(user.getPassword());

    user.setPassword(encodePwd);

    userMapper.save(user);

大體整合完成!

文章來源地址http://www.zghlxwxcb.cn/news/detail-695577.html

到了這里,關(guān)于spring security - 快速整合 springboot的文章就介紹完了。如果您還想了解更多內(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)文章

  • SpringBoot整合Spring Security實現(xiàn)權(quán)限控制

    SpringBoot整合Spring Security實現(xiàn)權(quán)限控制

    要對Web資源進行保護,最好的辦法莫過于Filter 要想對方法調(diào)用進行保護,最好的辦法莫過于AOP。 Spring Security進行認證和鑒權(quán)的時候,就是利用的一系列的Filter來進行攔截的。 如圖所示,一個請求想要訪問到API就會從左到右經(jīng)過藍線框里的過濾器,其中 綠色部分是負責(zé)認證的

    2024年02月15日
    瀏覽(17)
  • spring-security-oauth2-authorization-server(一)SpringBoot3.1.3整合

    spring-security-oauth2-authorization-server(一)SpringBoot3.1.3整合

    因為SpringBoot3.x是目前最新的版本,整合spring-security-oauth2-authorization-server的資料很少,所以產(chǎn)生了這篇文章,主要為想嘗試SpringBoot高版本,想整合最新的spring-security-oauth2-authorization-server的初學(xué)者,旨在為大家提供一個簡單上手的參考,如果哪里寫得不對或可以優(yōu)化的還請大家

    2024年02月03日
    瀏覽(18)
  • 快速上手Spring Boot整合,開發(fā)出優(yōu)雅可靠的Web應(yīng)用!

    快速上手Spring Boot整合,開發(fā)出優(yōu)雅可靠的Web應(yīng)用!

    SpringBoot 是由 Pivotal 團隊提供的全新框架,其設(shè)計目的是用來 簡化 Spring 應(yīng)用的 初始搭建 以及 開發(fā)過程 。 使用了 Spring 框架后已經(jīng)簡化了我們的開發(fā)。而 SpringBoot 又是對 Spring 開發(fā)進行簡化的,可想而知 SpringBoot 使用的簡單及廣泛性。既然 SpringBoot 是用來簡化 Spring 開發(fā)的,

    2024年02月21日
    瀏覽(23)
  • Springboot 實踐(13)spring boot 整合RabbitMq

    前文講解了RabbitMQ的下載和安裝,此文講解springboot整合RabbitMq實現(xiàn)消息的發(fā)送和消費。 1、創(chuàng)建web project項目,名稱為“SpringbootAction-RabbitMQ” 2、修改pom.xml文件,添加amqp使用jar包 ?? !--? RabbitMQ -- ??? ????dependency ??????????? groupIdorg.springframework.boot/groupId ????????

    2024年02月09日
    瀏覽(23)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 gateway 完成授權(quán)認證(擁抱 springboot 3.1)

    Spring Security Oauth2.1 最新版 1.1.0 整合 gateway 完成授權(quán)認證(擁抱 springboot 3.1)

    目錄 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基礎(chǔ) spring security OAuth2 模塊構(gòu)成 授權(quán)方式 認證方式 集成過程 官方demo 代碼集成 依賴 授權(quán)服務(wù)AuthorizationServerConfig配置 重要組件 測試 查看授權(quán)服務(wù)配置 訪問授權(quán)服務(wù) 授權(quán) 回調(diào) 獲取?access_token 獲取用戶信息 個性

    2024年02月08日
    瀏覽(19)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 (基于 springboot 3.1.0)gateway 完成授權(quán)認證

    Spring Security Oauth2.1 最新版 1.1.0 整合 (基于 springboot 3.1.0)gateway 完成授權(quán)認證

    目錄 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基礎(chǔ) spring security OAuth2 模塊構(gòu)成 授權(quán)方式 認證方式 集成過程 官方demo 代碼集成 依賴 授權(quán)服務(wù)AuthorizationServerConfig配置 重要組件 測試 查看授權(quán)服務(wù)配置 訪問授權(quán)服務(wù) 授權(quán) 回調(diào) 獲取?access_token 獲取用戶信息 個性

    2024年02月11日
    瀏覽(24)
  • 【SpringBoot】Spring Boot 項目中整合 MyBatis 和 PageHelper

    目錄 前言? ? ? ?? 步驟 1: 添加依賴 步驟 2: 配置數(shù)據(jù)源和 MyBatis 步驟 3: 配置 PageHelper 步驟 4: 使用 PageHelper 進行分頁查詢 IDEA指定端口啟動 總結(jié) ????????Spring Boot 與 MyBatis 的整合是 Java 開發(fā)中常見的需求,特別是在使用分頁插件如 PageHelper 時。PageHelper 是一個針對 MyBat

    2024年04月25日
    瀏覽(32)
  • 【Spring Boot】SpringBoot 優(yōu)雅整合Swagger Api 自動生成文檔

    【Spring Boot】SpringBoot 優(yōu)雅整合Swagger Api 自動生成文檔

    Swagger 是一套 RESTful API 文檔生成工具,可以方便地生成 API 文檔并提供 API 調(diào)試頁面。 而 Spring Boot 是一款非常優(yōu)秀的 Java Web 開發(fā)框架,它可以非常方便地構(gòu)建 Web 應(yīng)用程序。 在本文中,我們將介紹如何使用 Swagger 以及如何在 Spring Boot 中整合 Swagger 。 首先,在 pom.xml 文件中添

    2023年04月22日
    瀏覽(25)
  • SpringBoot-1-Spring Boot實戰(zhàn):快速搭建你的第一個應(yīng)用,以及了解原理

    SpringBoot-1-Spring Boot實戰(zhàn):快速搭建你的第一個應(yīng)用,以及了解原理

    SpringBootWeb入門 我們在之前介紹Spring的時候,已經(jīng)說過Spring官方(Spring官方)提供很多開源項目,點擊projects,看到spring家族旗下的項目 Spring發(fā)展到今天已經(jīng)形成了一種開發(fā)生態(tài)圈,Spring提供了若干個子項目,每個項目用于完成特定的功能。而我們在項目開發(fā)時,一般會偏向于選

    2024年02月12日
    瀏覽(92)
  • Spring Boot學(xué)習(xí)隨筆-第一個SpringBoot項目快速啟動(org.springframework.boot、@SpringBootApplication、application.yml)

    Spring Boot學(xué)習(xí)隨筆-第一個SpringBoot項目快速啟動(org.springframework.boot、@SpringBootApplication、application.yml)

    學(xué)習(xí)視頻:【編程不良人】2021年SpringBoot最新最全教程 創(chuàng)建第一個Module 環(huán)境要求 jdk1.8+ maven3.2+ Spring Framework 5.x+ Tomcat 9.0+ IDEA 2021 自動保存刷新pom 在resources下添加application.yml文件后,即可啟動springboot應(yīng)用 由于tomcat內(nèi)嵌在springboot里面了,所以我們在修改端口號等設(shè)置也在配置

    2024年02月05日
    瀏覽(38)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包