SpringSecurity在單機(jī)環(huán)境下使用方法詳解
參考
來源于黑馬程序員: 手把手教你精通新版SpringSecurity
技術(shù)選型
SpringBoot2.1.3,SpringSecurity,MySQL,mybatis,jsp
初步整合認(rèn)證第一版
創(chuàng)建工程并導(dǎo)入jar包
先只導(dǎo)入SpringBoot
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>提供處理器
@Controller
@RequestMapping("/product")
public class ProductController {
@RequestMapping
@ResponseBody
public String hello(){
return "success";
}
}編寫啟動類
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}測試效果
使用SpringBoot內(nèi)置tomcat啟動項目,即可訪問處理器。

加入SpringSecurity的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>重啟再次測試
SpringBoot已經(jīng)為SpringSecurity提供了默認(rèn)配置,默認(rèn)所有資源都必須認(rèn)證通過才能訪問。

那么問題來了!此刻并沒有連接數(shù)據(jù)庫,也并未在內(nèi)存中指定認(rèn)證用戶,如何認(rèn)證呢?
其實SpringBoot已經(jīng)提供了默認(rèn)用戶名user,密碼在項目啟動時隨機(jī)生成,如圖:

認(rèn)證通過后可以繼續(xù)訪問處理器資源:

整合認(rèn)證第二版
加入jsp,使用自定義認(rèn)證頁面
說明
SpringBoot官方是不推薦在SpringBoot中使用jsp的,那么到底可以使用嗎?答案是肯定的!
不過需要導(dǎo)入tomcat插件啟動項目,不能再用SpringBoot默認(rèn)tomcat了。
我們不能 通過啟動類的方式來進(jìn)行啟動了,因為它會不識別Jsp頁面,必須導(dǎo)入jar包,然后更換方法
導(dǎo)入SpringBoot的tomcat啟動插件jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>加入jsp頁面等靜態(tài)資源
在src/main目錄下創(chuàng)建webapp目錄

這時webapp目錄并不能正常使用,因為只有web工程才有webapp目錄,在pom文件中修改項目為web工程

這時webapp目錄,可以正常使用了!

導(dǎo)入第一天案例中靜態(tài)資源,注意WEB-INF就不用了哈!

修改login.jsp中認(rèn)證的url地址

修改header.jsp中退出登錄的url地址

提供SpringSecurity配置類
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//指定認(rèn)證對象的來源
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.jsp")
.loginProcessingUrl("/login")
.successForwardUrl("/index.jsp")
.failureForwardUrl("/failer.jsp")
.and()
.logout()
.logoutSuccessUrl("/logout")
.invalidateHttpSession(true)
.logoutSuccessUrl("/login.jsp")
.and()
.csrf()
.disable();
}
}修改產(chǎn)品處理器
有頁面了,就跳轉(zhuǎn)一個真的吧!
@Controller
@RequestMapping("/product")
public class ProductController {
@RequestMapping("/findAll")
public String findAll(){
return "product-list";
}
}配置視圖解析器

使用tomcat插件啟動項目

測試效果
自定義的認(rèn)證頁面

認(rèn)證成功頁面

整合認(rèn)證第三版【數(shù)據(jù)庫認(rèn)證】 數(shù)據(jù)庫環(huán)境準(zhǔn)備
依然使用security_authority數(shù)據(jù)庫,sql語句在第一天資料里。
導(dǎo)入數(shù)據(jù)庫操作相關(guān)jar包
<!--MySQL驅(qū)動包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--springboot啟動類-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<!--導(dǎo)入通用Mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>在配置文件中添加數(shù)據(jù)庫操作相關(guān)配置

在啟動類上添加掃描dao接口包注解

創(chuàng)建用戶pojo對象
這里直接實現(xiàn)SpringSecurity的用戶對象接口,并添加角色集合私有屬性。注意接口屬性都要標(biāo)記不參與json的處理
@Data
public class SysRole implements GrantedAuthority {
private Integer id;
private String roleName;
private String roleDesc;
}創(chuàng)建角色pojo對象
這里直接使用SpringSecurity的角色規(guī)范,我們實現(xiàn)UserDetails的類型
@Data
public class SysUser implements UserDetails {
private Integer id;
private String username;
private String password;
private Integer status;
private List<SysRole> roles;
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
}提供角色mapper接口
public interface RoleMapper extends Mapper<SysRole> {
@Select("SELECT r.id, r.role_name roleName, r.role_desc roleDesc " +
"FROM sys_role r, sys_user_role ur " +
"WHERE r.id=ur.rid AND ur.uid=#{uid}")
public List<SysRole> findByUid(Integer uid);
}提供用戶mapper接口
這里就用到了Mybatis的一對多進(jìn)行操作
public interface UserMapper extends Mapper<SysUser> {
@Select("select * from sys_user where username = #{username}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "roles", column = "id", javaType = List.class,
many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid"))
})
public SysUser findByName(String username);
}提供認(rèn)證service接口
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return userMapper.findByUsername(s);
}
}在啟動類中把加密對象放入IOC容器
@SpringBootApplication
@MapperScan("com.itheima.mapper")
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}修改配置類
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//指定認(rèn)證對象的來源
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.jsp")
.loginProcessingUrl("/login")
.successForwardUrl("/index.jsp")
.failureForwardUrl("/failer.jsp")
.and()
.logout()
.logoutSuccessUrl("/logout")
.invalidateHttpSession(true)
.logoutSuccessUrl("/login.jsp")
.and()
.csrf()
.disable();
}
}大功告成盡管測試,注意還是用插件啟動項目,使用數(shù)據(jù)庫表中的用戶名和密碼。
整合實現(xiàn)授權(quán)功能
在啟動類上添加開啟方法級的授權(quán)注解

在產(chǎn)品處理器類上添加注解
要求產(chǎn)品列表功能必須具有ROLE_ADMIN角色才能訪問!

重啟項目測試
再次訪問產(chǎn)品列表發(fā)現(xiàn)權(quán)限不足

指定自定義異常頁面
編寫異常處理器攔截403異常
@ControllerAdvice
public class HandleControllerException {
@ExceptionHandler(RuntimeException.class)
public String exceptionHandler(RuntimeException e){
if(e instanceof AccessDeniedException){
//如果是權(quán)限不足異常,則跳轉(zhuǎn)到權(quán)限不足頁面!
return "redirect:/403.jsp";
}
//其余的異常都到500頁面!
return "redirect:/500.jsp";
}
}再次測試產(chǎn)品列表就可以到自定義異常頁面了

到此這篇關(guān)于SpringSecurity在單機(jī)環(huán)境下使用的文章就介紹到這了,更多相關(guān)SpringSecurity單機(jī)環(huán)境使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
調(diào)用java.lang.Runtime.exec的正確姿勢分享
這篇文章主要介紹了調(diào)用java.lang.Runtime.exec的正確姿勢,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
springboot2?使用activiti6?idea插件的過程詳解
這篇文章主要介紹了springboot2?使用activiti6?idea插件,本文通過截圖實例代碼相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
Struts 2 數(shù)據(jù)校驗功能及校驗問題的解決方案
這篇文章主要介紹了Struts 2 數(shù)據(jù)校驗功能及校驗問題的解決方案的相關(guān)資料,需要的朋友可以參考下2016-09-09
SpringBoot創(chuàng)建自定義Starter代碼實例
這篇文章主要介紹了SpringBoot創(chuàng)建自定義Starter代碼實例,自定義 Starter 是一種在軟件開發(fā)中常用的技術(shù),它可以幫助開發(fā)者快速搭建項目的基礎(chǔ)框架和配置,可以將一些常用的功能、依賴和配置封裝成一個可復(fù)用的模塊,方便在不同的項目中使用,需要的朋友可以參考下2023-11-11
java封裝空值建議使用Optional替代null的方法示例解析
這篇文章主要為大家介紹了java封裝空值建議使用Optional替代null的方法原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11

