解決spring security中遇到的問題
spring security中遇到的問題
1.An Authentication object was not found in the Security Context
在security上下文中沒有找到一個認證對象,我這邊的問題在于controller中方法添加了認證注解,但是配置類中

源自于一片我為了解決攔截靜態(tài)文件的博客,上面說這個忽視目錄會以classpath中的static文件夾,實際上這樣寫有著很大問題,這邊會讓所有的文件不攔截,雖然你的http認證添加了攔截,但是web這個會影響到效果,所以一邊允許所有文件不攔截,一邊controller中添加了需要認證的注解,所以你一訪問就會進去這個頁面,但是進去之后發(fā)現(xiàn)在security context并沒有這個角色值,所以就會出現(xiàn)這個異常
最后對這個異常說明一句話:這個普通來看就是越過了普通的往上下文中添加了角色但是進去了這個頁面就會出現(xiàn)這個錯誤
2.攔截登錄之后總是會進login?error,而且沒有提示
這個情況還是有錯誤提示才會好解決問題,在http認證配置中的FormLoginConfigurer添加一個failureUrl("/login/error"),當然這個地址是我們自己定義的,然后對應的congtroller方法:
@RequestMapping(value = "/login/error")
public void loginError(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
AuthenticationException exception =
(AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
try {
response.getWriter().write(exception.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
這樣就可以把最基本的錯誤打印出來,然后我們再根據(jù)實際問題進行處理
3.Spring Security BadCredentialsException
這個具體原因還不是很清楚,但是有個很簡單的解決辦法,把所有的密碼加密方式改為相同的,還不可以的話
單獨寫一個配置類:
@Configuration
public class BeanConfiguration {
/**
* @return Return to the custom password encryptor.
* The reason why it is extracted separately as a configuration class is because if you don't do this,
* you cannot achieve unified password encryption, which leads to login failures.
* Different password encryption results in different passwords.
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new CustomPasswordEncoder();
}
}
這個CustomPasswordEncoder類是我自己寫個一個密碼加密類,不想使用的話也可以使用官方推薦的:BCryptPasswordEncoder
springboot用security遇到的問題
如果項目中用了 security ,而不用 security 自帶的登入的話 ,會自動跳轉其自帶的登入界面(前提是已攔截 放開的可以直接訪問),/login 自帶登入接口路徑 ,/logout 自帶退出接口路勁。
自定義攔截
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**/*.css","/**/*.js","/**/*.jpg","/**/*.gif","/**/*.ico","/**/*.ico","/**/*.woff","/**/*.ttf","/**/*.png").permitAll()
// .antMatchers("/main").hasAnyRole("ANONYMOUS,USER")
.anyRequest().authenticated()
.and().csrf().disable()
//指定支持基于表單的身份驗證。如果未指定FormLoginConfigurer#loginPage(String),則將生成默認登錄頁面
.formLogin() // 此開始
.loginPage("/login") //security 自帶登入接口
.permitAll()
.and() //此結束
.headers().frameOptions().disable()
.and()
.rememberMe().tokenValiditySeconds(1209600)
.and()
.logout()
.permitAll();
}
}
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot+JWT實現(xiàn)單點登錄完美解決方案
單點登錄是一種統(tǒng)一認證和授權機制,指在多個應用系統(tǒng)中,用戶只需要登錄一次就可以訪問所有相互信任的系統(tǒng),不需要重新登錄驗證,這篇文章主要介紹了SpringBoot+JWT實現(xiàn)單點登錄解決方案,需要的朋友可以參考下2023-07-07
SpringAOP切點函數(shù)實現(xiàn)原理詳解
這篇文章主要介紹了SpringAOP切點函數(shù)實現(xiàn)原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05

