1. 程式人生 > >spring boot下配置spring security筆記(請面試官進來看看)

spring boot下配置spring security筆記(請面試官進來看看)

springboot所有的配置是無xml的,用webinitlizer繼承

AbstractAnnotationConfigDispatcherServletInitializer

配置攔截器等

在實現類中getServletFilters
DelegatingFilterProxy securityFilterChain = new DelegatingFilterProxy("springSecurityFilterChain");
return new Filter[] {characterEncodingFilter, securityFilterChain};
就可以開啟攔截了

在實現類中

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[]{RootConfig.class,SecurityConfig.class};
}
就可以註冊一個攔截相關的實現類實現auto認證與http認證啦!!!

===================================ruo======================================

以下為我遇到的錯誤資訊

1.csrfException,場景,因為我是通過webservice呼叫的 屬於無狀態請求,所以需要在securityConfig裡設定.and().csrf().disable()禁用即可

2.AccessDeniedException: Access is denied

這個是指我沒有訪問這個url地址的許可權

3.

loadUserByUsername(String username)
soa架構下萬年獲取不到username的問題,這個教科書和百度上並沒有具體的告訴我
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/loginProcessing")

4.InternalAuthenticationService

UserAccountEntity類實現spring的 org.springframework.security.core.userdetails.UserDetails實現equals與hashCode方法

@Override
public boolean equals(Object rhs) {
    if (!(rhs instanceof User) || (rhs == null)) {
        return false;
}
    User user = (User) rhs;
    return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())
            && (this.isAccountNonExpired() == user.isAccountNonExpired())
            && (this.isAccountNonLocked() == user.isAccountNonLocked())
            && (this.isCredentialsNonExpired() == user.isCredentialsNonExpired())
            && (this.isEnabled() == user.isEnabled()));
}

@Override
public int hashCode() {
    int code = 9792;
    for (GrantedAuthority authority : getAuthorities()) {
        code = code * (authority.hashCode() % 7);
}

    if (this.getPassword() != null) {
        code = code * (this.getPassword().hashCode() % 7);
}

    if (this.getUsername() != null) {
        code = code * (this.getUsername().hashCode() % 7);
}

    if (this.isAccountNonExpired()) {
        code = code * -2;
}

    if (this.isAccountNonLocked()) {
        code = code * -3;
}

    if (this.isCredentialsNonExpired()) {
        code = code * -5;
}

    if (this.isEnabled()) {
        code = code * -7;
}

    return code;
}

5.客戶端請求這個,不要去請求login這個地址

org.springframework.security.authentication.BadCredentialsException: Bad credentials

DaoAuthenticationProvider
if(!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
這是由於我密碼配置錯誤導致的,讓我們加到config auth這個方法
auth.userDetailsService(spitterUserService).passwordEncoder(new BCryptPasswordEncoder());
改成
auth.userDetailsService(spitterUserService).passwordEncoder(new Md5PasswordEncoder());

即可

6.問:如果不讓springboot重定向 並且返回json

答:這個問題問的好,這是人唯一沒有參照網上資料自己根據意思研發出來的

SecurityConfig 中

.and()
    .formLogin()
    .loginPage("/login")
    .loginProcessingUrl("/loginProcessing")
    .successHandler(new AuthSeuccessHandlerController())
配置
public class AuthSeuccessHandlerController extends BaseController implements AuthenticationSuccessHandler
在 onAuthenticationSuccess 實現方法中 authentication 引數就有你的使用者資訊了 你不必要再去資料庫查一遍了
通過reponse就可以返回json了 你可以隨便折騰

配置了successHandler他就不會再重寫向到專案+/了

=======================================ruo=========================================

第二部分 資源認證

當我不是用AOP架構進行認證時 就沒有第二部分了

當spring security認證通過後會通過SecurityContextHolder儲存在上下文之中

那麼我的AOP如何才能與Authentication 進行匹配呢?答案是不可能除非重寫一大堆filter

我採用的是token進行傳輸

我重寫了restTemplate工具類 多封裝了token進去了

接下來是重點:

.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {

                    @Override
public <O extends FilterSecurityInterceptor> O postProcess(O fsi) {
                        fsi.setAccessDecisionManager(new AccessDecisionManagerImpl(userAccountRepository));
/*fsi.setAuthenticationManager(authenticationManagerBean());*/
return fsi;
}
                })
//                .expressionHandler(new AbstractAuthenticationProcessingFilter())
.antMatchers("/").permitAll()
                    .antMatchers("/menu/root").access("ROLE_ADMIN")
這是我的認證核心,重寫了FilterSecurityInterceptor,我是沒有辦法,因為無論是GET 還是 POST還是其它請求都無法通過UsernamePasswordAuthenticationFilter 如果未通過 那麼security會新增一個認證 那就是AnonymousAuthenticationFilter那麼Authentication 就是匿名使用者了,迴歸正題:我們用一個類實現AccessDecisionManager 重寫decide,方法中有如下引數
Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes

authentication就是認證資訊, 這個咱們不用管,基本就是匿名認證使用者,因為這是aop架構,o就是咱們的請求url,configAttribute就是角色資訊,請參照SecurityConfig裡的配置,如果我要攔截哪個路徑並且只允許哪個角色訪問那麼這個類就包含了這些角色資訊。

而為什麼需要token 我們是需要往資料庫裡面查一遍user並且與這個configAttributes進行認證匹配的,如果匹配成功就reutrn;不成功就丟擲異常。

相關推薦

spring boot配置spring security筆記面試進來看看

springboot所有的配置是無xml的,用webinitlizer繼承 AbstractAnnotationConfigDispatcherServletInitializer 配置攔截器等 在實現類中getServletFilters DelegatingFil

Spring Boot MyBatis配置Druid多資料來源附原始碼

Spring Boot MyBatis配置Druid多資料來源 回顧在Spring中配置MyBatis SqlSessionFactory的配置: <!-- mybatis 的SqlSessionFactory --> <bean id="sqlSessionF

Spring Boot自動配置原理與實踐

前言   Spring Boot眾所周知是為了簡化Spring的配置,省去XML的複雜化配置(雖然Spring官方推薦也使用Java配置)採用Java+Annotation方式配置。如下幾個問題是我剛開始接觸Spring Boot的時候經常遇到的一些疑問,現在總結出來希望能幫助到更多的人理解Spring B

Spring Boot 使用 Spring Batch

公司有個小需求,就是將老平臺使用者資訊和使用者的資產資訊遷移到新平臺上。功能是實現起來是很簡單。大概流程: 1.讀取老平臺使用者 2.將讀取到老平臺使用者資訊轉成新平臺使用者資訊(還有其他的基本資訊)的bean。 3.將bean寫入到新平臺。 這時突然想到了Spr

Centos7配置Java web環境JDK、Tomcat、Mysql

sql ner route aio word client rpm node share 在Centos7中配置java web環境主要涉及三方面配置:JDK、Tomcat以及Mysql 這裏使用版本如下: JDK:jdk-8u181-linux-x64,下載地址:http

Linux配置MySQL主從同步不復雜,簡單明瞭

明人不說暗話,直接進入正題 一、準備工作 假設兩個伺服器IP如下: 主伺服器:44.92.163.112    -Linux 從伺服器:114.74.22.11     -Linux 注意: 1、主從資料庫版本最好一致; 2、主從資料庫內資料保持一致;

kafka學習筆記(三)spring boot整合kafka0.9.0.1使用配置

spring boot 版本:1.5.6引入關於kafka的相關jar         <dependency>          <groupId>org.springframework.kafka</groupI

攜程 Apollo 配置中心 | 學習筆記 自定義Spring Boot專案通過配置中心啟動專案

一、前言二、專案搭建   2.1 建立Spring Boot專案    因為專案用的是Eureka作為服務註冊與發現,因此這裡我加入了Eureka Client的依賴pom.xml檔案 <dependency> <grou

ActiveMQ 基於zookeeper的主從levelDB Master/Slave搭建以及Spring-boot使用

tina true listener 報文 string ext 說明 下使用 nat 0:說明   ActiveMQ 5.9.0新推出的主從實現,基於zookeeper來選舉出一個master,其他節點自動作為slave實時同步消息。因為有實時同步數據的slave的存在,

企業分布式微服務雲SpringCloud SpringBoot mybatis Spring Boot屬性配置文件詳解

public profile 功能 tps with oot oschina 基本 ava 相信很多人選擇Spring Boot主要是考慮到它既能兼顧Spring的強大功能,還能實現快速開發的便捷。我們在Spring Boot使用過程中,最直觀的感受就是沒有了原來自己整合S

企業分布式微服務雲SpringCloud SpringBoot mybatis Spring Boot中使用Spring Security進行安全控制

spring ron public 控制 應用 app ebs cloud 來源 準備工作 首先,構建一個簡單的Web工程,以用於後續添加安全控制,也可以用之前Chapter3-1-2做為基礎工程。若對如何使用Spring Boot構建Web應用,可以先閱讀《Spring

Spring Boot自動配置原理

腳本 bst file ade hazelcast oauth dbd 參考 b-s 第3章 Spring Boot自動配置原理3.1 SpringBoot的核心組件模塊首先,我們來簡單統計一下SpringBoot核心工程的源碼java文件數量:我們

Sping Boot入門到實戰之入門篇Spring Boot屬性配置

git 測試 add 禁用 rop fix ron org set   該篇為Sping Boot入門到實戰系列入門篇的第三篇。介紹Spring Boot的屬性配置。   傳統的Spring Web應用自定義屬性一般是通過添加一個demo.properties配置文件(

03) spring Boot配置

oot pro 創建 yml ref tps wid 一個 etag 1. spring boot 的核心配置 spring boot 項目建立之後,已經創建好了application.properties 配置文件 其實, 配置文件還支持*.yml 格式的; 2. 多配

spring-boot configuration processor 讓配置檔案有提示不包括自定義的

IDEA新建spring-boot時  勾選該項   勾選該項後pom.xml就會出現 <dependency> <groupId>org.springframework.boot</groupId> <

Spring Boot22Spring Boot啟動配置原理

啟動配置原理 重要的事件回撥機制: ApplicationContextInitializer SpringApplicationRunListener ApplicationRunner CommandLineRunner前兩者需要配置在META-INF/spring.f

spring-boot configuration processor 讓配置檔案有提示不包括自定義的

IDEA新建spring-boot時  勾選該項 勾選該項後pom.xml就會出現 <dependency> <groupId>org.springframework.boot</groupId> <art

Spring Boot 自動配置auto-configurtion 揭祕

本章,我們為你揭祕Spring Boot自動配置(Auto Configuration)執行機制,談到auto-configuration,肯定離不開@EnableAutoConfiguration註解。 package org.springframework.

2018年最新Spring Boot視訊教程附程式碼筆記資料50G

一共6套 SpringBoot 學習視訊,這裡只列了4套,剩下2套,大家關注後自己去看! 1. Spring Boot  專案實戰 ----- 技術棧部落格企業前後端   2.Spring Boot  專案實戰 -----傳智播客Spring Boot視訊教程附

Spring boot logback 日誌系統配置

<?xml version="1.0" encoding="UTF-8"?> <!-- scan:當此屬性設定為true時,配置檔案如果發生改變,將會被重新載入,預設值為true。 scanPeriod:設定監測配置檔案是否有修改的時間間隔,如果沒有給出時間單位,預設單位是