Spring security OAuth2.0認證授權學習第四天(SpringBoot集成)


基礎的授權其實只有兩行代碼就不單獨寫一個篇章了;

 

這兩行就是上一章demo的權限判斷;

集成SpringBoot

SpringBoot介紹

 

 

 這個篇章主要是講SpringSecurity的,SpringBoot不做主要講解

創建SpringBoot項目

在這里說一下,我的所有項目創建和代碼的書寫都是使用的IDEA,eclipse我用的不是很明白;

點擊File -> new Project

 

 

 我用的是Spring初始化

 

 

 

 配置Maven信息后點擊下一步

 

 

 在這里我選擇了Lombok.web,和security

 

 

 一些路徑的配置,

在POM.xml中我除了選擇的又增加了Servlet的依賴

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
            <scope>provided</scope>
        </dependency>

 

springboot工程會在啟動時自動掃描啟動類所在包中的所有類及其子包子類加載到Spring容器中,所以不再需要SpringConfig.java的配置類

在工程中會有一個application.properties的配置文件,當然也可以換為yml的,我們公司統一使用yml的

在這個類里面配置就可以了

# 端口號
server.port=8080
# 上下文路徑
server.servlet.context-path=/abc
# spring 應用程序名
spring.application.name=security

配置SpringWeb的配置類

 1 package com.dance.flower.springbootsecurity.config;
 2 
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 6 
 7 /**
 8  * @Description web配置類
 9  * @ClassName SpingWebConfig
10  * @Author mr.zhang
11  * @Date 2020/5/10 23:31
12  * @Version 1.0.0
13  **/
14 @Configuration
15 public class SpingWebConfig implements WebMvcConfigurer {
16 
17     @Override
18     public void addViewControllers(ViewControllerRegistry registry) {
19         registry.addViewController("/").setViewName("redirect:/login");
20     }
21 }

視圖解析器也不需要了,也配置在了application.properties中

# 視圖前綴
spring.mvc.view.prefix=/WEB-INF/views/
# 視圖后綴
spring.mvc.view.suffix=.jsp

springsecurity的配置是一樣的,拷貝一下,把注解換為@Configuration

 1 package com.dance.flower.springbootsecurity.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 6 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 7 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 8 import org.springframework.security.core.userdetails.User;
 9 import org.springframework.security.core.userdetails.UserDetailsService;
10 import org.springframework.security.crypto.password.NoOpPasswordEncoder;
11 import org.springframework.security.crypto.password.PasswordEncoder;
12 import org.springframework.security.provisioning.InMemoryUserDetailsManager;
13 
14 /**
15  * @Description 安全配置
16  * @ClassName WebSecurityConfig
17  * @Author mr.zhang
18  * @Date 2020/5/6 17:58
19  * @Version 1.0.0
20  **/
21 @Configuration
22 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
23 
24     /**
25      * 定義用戶信息服務(查詢用戶信息)
26      * @return UserDetailsService
27      */
28     @Bean
29     @Override
30     public UserDetailsService userDetailsService(){
31         // 基於內存比對
32         InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
33         // 創建用戶
34         inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("zs").authorities("p1").build());
35         inMemoryUserDetailsManager.createUser(User.withUsername("ls").password("ls").authorities("p2").build());
36         return inMemoryUserDetailsManager;
37     }
38 
39     /**
40      * 密碼編碼器
41      * @return PasswordEncode
42      */
43     @Bean
44     public PasswordEncoder passwordEncoder(){
45         // 暫時采用字符串比對
46         return NoOpPasswordEncoder.getInstance();
47     }
48 
49     /**
50      * 安全攔截機制
51      * @param http
52      * @throws Exception
53      */
54     @Override
55     protected void configure(HttpSecurity http) throws Exception {
56         // 認證請求
57         http.authorizeRequests()
58                 .antMatchers("/r/r1").hasAuthority("p1")
59                 .antMatchers("/r/r2").hasAuthority("p2")
60                 // 需要認證
61                 .antMatchers("/r/**").authenticated()
62                 // 其他的放行
63                 .anyRequest().permitAll()
64                 // 並且
65                 .and()
66                 // 允許表單登錄
67                 .formLogin()
68                 // 成功后轉發地址
69                 .successForwardUrl("/success");
70     }
71 }

Controller直接拷貝

 1 package com.dance.flower.springbootsecurity.controller;
 2 
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 /**
 7  * @Description 認證控制器
 8  * @ClassName AuthService
 9  * @Author mr.zhang
10  * @Date 2020/5/2 17:40
11  * @Version 1.0.0
12  **/
13 @RestController
14 public class AuthController {
15 
16     @RequestMapping(value = "/r/r1",produces = {"application/json;charset=UTF-8"})
17     public String r1(){
18         return "訪問資源r1";
19     }
20 
21     @RequestMapping(value = "/r/r2",produces = {"application/json;charset=UTF-8"})
22     public String r2(){
23         return "訪問資源r2";
24     }
25 
26     /**
27      * 成功后跳轉 提供給SpringSecurity使用
28      * @return
29      */
30     @RequestMapping(value="/success",produces = ("text/plain;charset=UTF-8"))
31     public String loginSuccess(){
32         return "登錄成功";
33     }
34 
35 
36 }

開始啟動.....  運行Main方法

我就知道我的啟動不會是一帆風順的,好吧,報錯了,檢查之后發現,還是自己作的原因,為啥要在POM.xml中添加Servlet依賴呢,自己也很迷糊,注釋掉了,重新啟動成功

 

 不用在意8080后的那個名字,本來是abc,在我排查錯誤的時候,以為是context-path和application.name不一致的問題,后來重試了一下,發現不是,,所以不用在意

 

用戶名密碼還是之前配置的么有變

洗洗睡了

作者:彼岸舞

時間:2020\05\10

內容關於:spring security

本文部分來源於網絡,只做技術分享,一概不負任何責任

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM