SpringSecurity在單機(jī)環(huán)境下使用方法詳解
參考
來(lái)源于黑馬程序員: 手把手教你精通新版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"; } }
編寫(xiě)啟動(dòng)類(lèi)
@SpringBootApplication public class SecurityApplication { public static void main(String[] args) { SpringApplication.run(SecurityApplication.class, args); } }
測(cè)試效果
使用SpringBoot內(nèi)置tomcat啟動(dòng)項(xiàng)目,即可訪(fǎng)問(wèn)處理器。
加入SpringSecurity的jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
重啟再次測(cè)試
SpringBoot已經(jīng)為SpringSecurity提供了默認(rèn)配置,默認(rèn)所有資源都必須認(rèn)證通過(guò)才能訪(fǎng)問(wèn)。
那么問(wèn)題來(lái)了!此刻并沒(méi)有連接數(shù)據(jù)庫(kù),也并未在內(nèi)存中指定認(rèn)證用戶(hù),如何認(rèn)證呢?
其實(shí)SpringBoot已經(jīng)提供了默認(rèn)用戶(hù)名user,密碼在項(xiàng)目啟動(dòng)時(shí)隨機(jī)生成,如圖:
認(rèn)證通過(guò)后可以繼續(xù)訪(fǎng)問(wèn)處理器資源:
整合認(rèn)證第二版
加入jsp,使用自定義認(rèn)證頁(yè)面
說(shuō)明
SpringBoot官方是不推薦在SpringBoot中使用jsp的,那么到底可以使用嗎?答案是肯定的!
不過(guò)需要導(dǎo)入tomcat插件啟動(dòng)項(xiàng)目,不能再用SpringBoot默認(rèn)tomcat了。
我們不能 通過(guò)啟動(dòng)類(lèi)的方式來(lái)進(jìn)行啟動(dòng)了,因?yàn)樗鼤?huì)不識(shí)別Jsp頁(yè)面,必須導(dǎo)入jar包,然后更換方法
導(dǎo)入SpringBoot的tomcat啟動(dòng)插件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頁(yè)面等靜態(tài)資源
在src/main目錄下創(chuàng)建webapp目錄
這時(shí)webapp目錄并不能正常使用,因?yàn)橹挥衱eb工程才有webapp目錄,在pom文件中修改項(xiàng)目為web工程
這時(shí)webapp目錄,可以正常使用了!
導(dǎo)入第一天案例中靜態(tài)資源,注意WEB-INF就不用了哈!
修改login.jsp中認(rèn)證的url地址
修改header.jsp中退出登錄的url地址
提供SpringSecurity配置類(lèi)
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled=true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } //指定認(rèn)證對(duì)象的來(lái)源 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)品處理器
有頁(yè)面了,就跳轉(zhuǎn)一個(gè)真的吧!
@Controller @RequestMapping("/product") public class ProductController { @RequestMapping("/findAll") public String findAll(){ return "product-list"; } }
配置視圖解析器
使用tomcat插件啟動(dòng)項(xiàng)目
測(cè)試效果
自定義的認(rèn)證頁(yè)面
認(rèn)證成功頁(yè)面
整合認(rèn)證第三版【數(shù)據(jù)庫(kù)認(rèn)證】 數(shù)據(jù)庫(kù)環(huán)境準(zhǔn)備
依然使用security_authority數(shù)據(jù)庫(kù),sql語(yǔ)句在第一天資料里。
導(dǎo)入數(shù)據(jù)庫(kù)操作相關(guān)jar包
<!--MySQL驅(qū)動(dòng)包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--springboot啟動(dòng)類(lèi)--> <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ù)庫(kù)操作相關(guān)配置
在啟動(dòng)類(lèi)上添加掃描dao接口包注解
創(chuàng)建用戶(hù)pojo對(duì)象
這里直接實(shí)現(xiàn)SpringSecurity的用戶(hù)對(duì)象接口,并添加角色集合私有屬性。注意接口屬性都要標(biāo)記不參與json的處理
@Data public class SysRole implements GrantedAuthority { private Integer id; private String roleName; private String roleDesc; }
創(chuàng)建角色pojo對(duì)象
這里直接使用SpringSecurity的角色規(guī)范,我們實(shí)現(xiàn)UserDetails的類(lèi)型
@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); }
提供用戶(hù)mapper接口
這里就用到了Mybatis的一對(duì)多進(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); } }
在啟動(dòng)類(lèi)中把加密對(duì)象放入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(); } }
修改配置類(lèi)
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled=true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } //指定認(rèn)證對(duì)象的來(lái)源 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(); } }
大功告成盡管測(cè)試,注意還是用插件啟動(dòng)項(xiàng)目,使用數(shù)據(jù)庫(kù)表中的用戶(hù)名和密碼。
整合實(shí)現(xiàn)授權(quán)功能
在啟動(dòng)類(lèi)上添加開(kāi)啟方法級(jí)的授權(quán)注解
在產(chǎn)品處理器類(lèi)上添加注解
要求產(chǎn)品列表功能必須具有ROLE_ADMIN角色才能訪(fǎng)問(wèn)!
重啟項(xiàng)目測(cè)試
再次訪(fǎng)問(wèn)產(chǎn)品列表發(fā)現(xiàn)權(quán)限不足
指定自定義異常頁(yè)面
編寫(xiě)異常處理器攔截403異常
@ControllerAdvice public class HandleControllerException { @ExceptionHandler(RuntimeException.class) public String exceptionHandler(RuntimeException e){ if(e instanceof AccessDeniedException){ //如果是權(quán)限不足異常,則跳轉(zhuǎn)到權(quán)限不足頁(yè)面! return "redirect:/403.jsp"; } //其余的異常都到500頁(yè)面! return "redirect:/500.jsp"; } }
再次測(cè)試產(chǎn)品列表就可以到自定義異常頁(yè)面了
到此這篇關(guān)于SpringSecurity在單機(jī)環(huán)境下使用的文章就介紹到這了,更多相關(guān)SpringSecurity單機(jī)環(huán)境使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringSecurity在分布式環(huán)境下的使用流程分析
- SpringSecurity實(shí)現(xiàn)動(dòng)態(tài)權(quán)限校驗(yàn)的過(guò)程
- SpringBoot3.x接入Security6.x實(shí)現(xiàn)JWT認(rèn)證的完整步驟
- SpringSecurity安全框架的使用
- Spring?Clou整合?Security?+?Oauth2?+?jwt實(shí)現(xiàn)權(quán)限認(rèn)證的詳細(xì)過(guò)程
- Spring Security的持久化用戶(hù)和授權(quán)實(shí)現(xiàn)方式
相關(guān)文章
學(xué)會(huì)在Java中使用Optional功能
這篇文章主要介紹了學(xué)會(huì)在Java中使用Optional功能,在本文中,我們將了解如何、何時(shí)以及在哪里最好地應(yīng)用Optional,具體相關(guān)內(nèi)容需要的朋友可以參考下面文章內(nèi)容2022-09-09調(diào)用java.lang.Runtime.exec的正確姿勢(shì)分享
這篇文章主要介紹了調(diào)用java.lang.Runtime.exec的正確姿勢(shì),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11springboot2?使用activiti6?idea插件的過(guò)程詳解
這篇文章主要介紹了springboot2?使用activiti6?idea插件,本文通過(guò)截圖實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03Struts 2 數(shù)據(jù)校驗(yàn)功能及校驗(yàn)問(wèn)題的解決方案
這篇文章主要介紹了Struts 2 數(shù)據(jù)校驗(yàn)功能及校驗(yàn)問(wèn)題的解決方案的相關(guān)資料,需要的朋友可以參考下2016-09-09解決idea2020.1找不到程序包和符號(hào)的問(wèn)題
這篇文章主要介紹了解決idea2020.1找不到程序包和符號(hào)的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01SpringBoot創(chuàng)建自定義Starter代碼實(shí)例
這篇文章主要介紹了SpringBoot創(chuàng)建自定義Starter代碼實(shí)例,自定義 Starter 是一種在軟件開(kāi)發(fā)中常用的技術(shù),它可以幫助開(kāi)發(fā)者快速搭建項(xiàng)目的基礎(chǔ)框架和配置,可以將一些常用的功能、依賴(lài)和配置封裝成一個(gè)可復(fù)用的模塊,方便在不同的項(xiàng)目中使用,需要的朋友可以參考下2023-11-11java封裝空值建議使用Optional替代null的方法示例解析
這篇文章主要為大家介紹了java封裝空值建議使用Optional替代null的方法原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11