安全框架
在java開發領域,常見的安全管理框架有apache shiro和spring security。shiro是相對spring security是輕量級的,提供了認證、授權,會話管理,密碼管理、緩存管理等功能,spring security相對複雜點,功能比shiro更加強大,權限控制可以更精細,對OAuth2的支持也更友好,與spring框架無縫整合
spring security
簡單用法
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 必須引入starter-web 否則不是web項目,不可能localhost:8080訪問,連錯誤頁面都沒有-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
登錄頁面
訪問 http://localhost:8080,出現了security的登錄頁面,不管是什麼URL都跳登錄,默認用戶名是user,默認密碼是每次啓動項目隨機生成
// 啓動時,生成隨機密碼
Using generated security password: 6a83bc58-fad7-4a16-94a3-9bd73d6a2f2f
如果不想使用隨機密碼,可以在yml中配
spring:
security:
user: # 如果有了基於內存的認證,則此處配置不生效
name: admin
password: admin
roles: admin
postman訪問成功
基於內存的認證
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance(); //如果沒有的話,會報java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { //這是基於內存的配置,則yml中配置的不生效
auth.inMemoryAuthentication()
.withUser("admin3").password("admin3").roles("ADMIN", "USER")
.and()
.withUser("user").password("123").roles("USER");
}
}
如果你發現訪問任何頁面,都出現了上面的登錄頁面,八成是引入了security,刪除security即可解決,如果是因爲其他的依賴引入了security,就不太好刪除了,這時,下面的配置類可以解決,重寫 WebSecurityConfigurerAdapter即可
@Configuration
public class SecurityConfig {
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
return new WebSecurityConfigurerAdapter() {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().permitAll();
}
};
}
}