SpringSecurity快速入門(mén)
點(diǎn)擊上方“ java1234?”,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
66套java從入門(mén)到精通實(shí)戰(zhàn)課程分享
介紹
如何使用springboot中Spring-security
引入依賴包
<dependency>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-starter-securityartifactId>
????????dependency>
????????<dependency>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-starter-webartifactId>
????????dependency>啟動(dòng)項(xiàng)目,
localhost:8080/login?進(jìn)入頁(yè)面,需要輸入用戶名和密碼。用戶名為:user,密碼在控制臺(tái)輸出,去控制臺(tái)查找。
在配置文件中使用
#如果在代碼里配置了用戶信息 這個(gè)就不能使用了呢?
spring.security.user.name=admin
spring.security.user.password=123456
spring.security.user.roles=ADMIN啟動(dòng)項(xiàng)目,
localhost:8080/login?進(jìn)入頁(yè)面,需要輸入用戶名和密碼。用戶名為:admin,密碼:123456
在內(nèi)存中使用
(需要將配置文件里配置的注釋掉)
@Configuration
@EnableWebSecurity//啟用Spring security
@EnableGlobalMethodSecurity(prePostEnabled = true)//攔截@preAuthrize注解的配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
????@Autowired
????private PasswordEncoder encoder;//這個(gè)東西很重要
????@Override
????protected void configure(AuthenticationManagerBuilder auth) throws Exception {
????????/*
?????????* 基于內(nèi)存的方式構(gòu)建兩個(gè)賬戶
?????????* */
????????auth
????????????????.inMemoryAuthentication()
????????????????.passwordEncoder(new BCryptPasswordEncoder())
????????????????.withUser("admin")
????????????????.password(new BCryptPasswordEncoder()
????????????????????????.encode("123"))
????????????????.roles("admin");
????????//兩個(gè)構(gòu)建賬戶的方式 看著不同 其實(shí)是一樣的啊
????????auth
????????????????.inMemoryAuthentication()
????????????????.passwordEncoder(encoder)
????????????????.withUser("user")
????????????????.password(encoder
????????????????????????.encode("123"))
????????????????.roles("normal");
????}
}在內(nèi)存中定義認(rèn)證用戶,需要自己寫(xiě)一個(gè)類
WebSecurityConfig實(shí)現(xiàn)WebSecurityConfigurerAdapter類,重寫(xiě)其中的方法;
需要注意的是:在設(shè)置密碼的時(shí)候,需要是加密后的密碼,且要符合加密類型;
類上面的注解?
@EnableGlobalMethodSecurity開(kāi)啟后針對(duì)不同的方法,會(huì)驗(yàn)證其身份角色;
@RestController
public?class?HelloController?{
????@GetMapping(value = "/hello")
????public?String hello()?{
????????return?"HelloWorld";
????}
????@GetMapping(value = "/helloAdmin")
????@PreAuthorize("hasAnyRole('admin')")
????public?String helloAdmin()?{
????????return?"HelloWorld,helloAdmin";
????}
??
????@PreAuthorize("hasAnyRole('normal','admin')")
????@GetMapping(value = "/helloUser")
????public?String helloUser()?{
????????return?"HelloWorld,helloUser";
????}
}
驗(yàn)證:
進(jìn)入
localhost:8080/login,登錄 admin用戶,再訪問(wèn):localhost:8080/helloAdmin?,localhost:8080/helloUser均可訪問(wèn)成功;
重新登入 user用戶,再訪問(wèn)
localhost:8080/helloAdmin?,localhost:8080/helloUser,發(fā)現(xiàn)訪問(wèn)localhost:8080/helloAdmin時(shí)報(bào)錯(cuò),訪問(wèn)被禁止
使用數(shù)據(jù)庫(kù)
1 添加依賴,使具備查詢數(shù)據(jù)庫(kù)的能
<dependency>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
????<groupId>org.hsqldbgroupId>
????<artifactId>hsqldbartifactId>
????<scope>runtimescope>
dependency>hsqldb內(nèi)存數(shù)據(jù)庫(kù),jpa 連接數(shù)據(jù)庫(kù)
2 開(kāi)發(fā)一個(gè)根據(jù)用戶名查詢用戶信息的接口
public?interface?UserInfoService?{
????public?UserInfo findByUsername(String username);
}3 編寫(xiě)一個(gè)類CustomUserDetailsService實(shí)現(xiàn)接口UserDetailsService?重寫(xiě)loadUserByUsername方法
@Component
public?class?CustomUserDetailsService?implements?UserDetailsService?{
????@Autowired
????private?UserInfoService service;
????@Autowired
????private?PasswordEncoder encoder;
????@Override
????public?UserDetails loadUserByUsername(String s)?throws?UsernameNotFoundException {
????????UserInfo userInfo = service.findByUsername(s);
????????if?(userInfo == null) {
????????????throw?new?UsernameNotFoundException("not found : "?+ s);
????????}
????????List authorities = new?ArrayList<>();
????????authorities.add(new?SimpleGrantedAuthority("ROLE_"?+ userInfo.getRole().name()));
????????User userDetails = new?User(userInfo.getUsername(), encoder.encode(userInfo.getPassword()), authorities);
????????return?userDetails;
????}
} 1 此方法返回的是一個(gè)
UserDetails?實(shí)例,構(gòu)造方法中有3個(gè)參數(shù),分別為 用戶名,密碼,和權(quán)限列表;2 次用用到了查詢用戶信息的接口
注意:此處的密碼需要加密;權(quán)限需要前面拼接
ROLE(權(quán)限如果提前預(yù)存在數(shù)據(jù)庫(kù)已經(jīng)拼接過(guò),此處寫(xiě)法會(huì)不同)
4 在數(shù)據(jù)庫(kù)添加用戶
@Service
public?class?DataInit?{
????@Autowired
????private?UserInfoRepository userInfoRepository;
????@PostConstruct
????public?void?dataInit()?{
????????UserInfo user = new?UserInfo();
????????user.setUsername("user");
????????user.setPassword("123");
????????user.setRole(UserInfo.Role.normal);
????????userInfoRepository.save(user);
????????UserInfo admin = new?UserInfo();
????????admin.setUsername("admin");
????????admin.setPassword("123");
????????admin.setRole(UserInfo.Role.admin);
????????userInfoRepository.save(admin);
????}
}驗(yàn)證:
進(jìn)入
localhost:8080/login,登錄 admin用戶,再訪問(wèn):localhost:8080/helloAdmin?,localhost:8080/helloUser均可訪問(wèn)成功;
重新登入 user用戶,再訪問(wèn)
localhost:8080/helloAdmin?,localhost:8080/helloUser,發(fā)現(xiàn)訪問(wèn)localhost:8080/helloAdmin時(shí)報(bào)錯(cuò),訪問(wèn)被禁止
源代碼:https://github.com/liyiruo/bili-spring-security
版權(quán)聲明:本文為博主原創(chuàng)文章,遵循?CC 4.0 BY-SA?版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接和本聲明。
本文鏈接:
https://blog.csdn.net/l23456789o/article/details/107853160
粉絲福利:108本java從入門(mén)到大神精選電子書(shū)領(lǐng)取
???
?長(zhǎng)按上方二維碼?2 秒 回復(fù)「1234」即可獲取資料以及 可以進(jìn)入java1234官方微信群
感謝點(diǎn)贊支持下哈?
