當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringSecurity简单教程(源码开源免费提供)
生活随笔
收集整理的這篇文章主要介紹了
SpringSecurity简单教程(源码开源免费提供)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SpringSecurity菜鳥教程
一:簡單配置權限管理
SecurityConfg的配置
package com.example.demo11.config;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.PasswordEncoder;import java.util.Objects;@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return new PasswordEncoder() {@Overridepublic String encode(CharSequence charSequence) {return charSequence.toString();}@Overridepublic boolean matches(CharSequence charSequence, String s) {return Objects.equals(charSequence.toString(), s);}};}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("用戶").password("123").roles("vip1").and().withUser("管理員").password("123").roles("vip2").and().withUser("超級管理員").password("123").roles("vip1", "vip2");}//配置忽略掉的 URL 地址,一般用于js,css,圖片等靜態資源@Overridepublic void configure(WebSecurity web) throws Exception {//web.ignoring() 用來配置忽略掉的 URL 地址,一般用于靜態文件web.ignoring().antMatchers("/js/**", "/css/**", "/fonts/**", "/images/**", "/lib/**");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/css/**", "/js/**", "/images/**").permitAll();//開啟運行iframe嵌套頁面http.headers().frameOptions().disable();http.authorizeRequests().antMatchers("/level1/vip1").hasRole("vip1").antMatchers("/level2/vip2").hasRole("vip2");//沒有權限會到默認的登錄頁面http.formLogin();} }IndexController的代碼
package com.example.demo11.controller;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping;@Controller public class IndexController {@GetMapping("/index")public String index(){return "index";}@GetMapping("/level1/vip1")public String level1Vip1(){return "level1/vip1";}@GetMapping("/level2/vip2")public String level2Vip1(){return "level2/vip2";} }由于沒有設置springsecurity全部攔截,主頁可以允許所有人訪問
二:自定義登錄頁面,記住密碼
1自定義登陸頁面
改變SecurityConfig中的配置
這個需要自己寫一個登錄的接口
2.記住密碼和注銷功能
//開啟記住我功能,cookie接收,默認保存兩周,自定義接收其前端http.rememberMe().rememberMeParameter("remember");
注銷功能:
三:基于數據庫自定義的表單驗證
1.數據庫表
這里的登錄認證只涉及到三張表:用戶表(user)、角色表(role)、用戶角色中間表(user_role)。
注意:這里的role跟上面的例子相比多加了ROLE_前綴。這是因為之前的role都是通過springsecurity的api賦值過去的,他會自行幫我們加上這個前綴。但是現在我們使用的是自己的數據庫里面讀取出來的權限,然后封裝到自己的實體類中。所以這時候需要我們自己手動添加這個ROLE_前綴。經過測試如果不加ROLE_前綴的話,可以做數據庫的認證,但無法做授權
2.建實體類User,注意User需要實現UserDetails接口,并且實現該接口下的7個接口
package com.example.demo11.pojo;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails;import java.util.ArrayList; import java.util.Collection; import java.util.List;@Data @AllArgsConstructor @NoArgsConstructor public class User implements UserDetails {private Integer id;private String userName;private String passWord;private List<Role> roles;//該用戶對應的角色/*** 返回用戶的權限集合。* @return*/@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {List<SimpleGrantedAuthority> authorities = new ArrayList<>();for (Role role : roles){authorities.add(new SimpleGrantedAuthority(role.getName()));System.out.println(authorities);}return authorities;}/*** 返回賬號的密碼* @return*/@Overridepublic String getPassword() {return passWord;}/*** 返回賬號的用戶名* @return*/@Overridepublic String getUsername() {return userName;}/*** 賬號是否失效,true:賬號有效,false賬號失效。* @return*/@Overridepublic boolean isAccountNonExpired() {return true;}/*** 賬號是否被鎖,true:賬號沒被鎖,可用;false:賬號被鎖,不可用* @return*/@Overridepublic boolean isAccountNonLocked() {return true;}/*** 賬號認證是否過期,true:沒過期,可用;false:過期,不可用* @return*/@Overridepublic boolean isCredentialsNonExpired() {return true;}/*** 賬號是否可用,true:可用,false:不可用* @return*/@Overridepublic boolean isEnabled() {return true;} }角色表實體類Role,這個類不用實現上述接口
package com.zsc.po;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;@Data @NoArgsConstructor @AllArgsConstructor public class Role {private Integer id;private String name;//角色的名字 }接下來做數據庫的查詢,創建持久層接口(UserMapper和RoleMapper)
package com.example.demo.mapper;import com.example.demo.pojo.Role; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository;import java.util.List;@Mapper @Repository public interface RoleMapper {/*** 通過用戶id獲取用戶角色集合** @param userId 用戶id* @return List<Role> 角色集合*/List<Role> getRolesByUserId(Integer userId);} package com.example.demo.mapper;import com.example.demo.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository;import java.util.List;@Mapper @Repository public interface UserMapper {/*** 通過用戶名獲取用戶信息** @param username 用戶名* @return User 用戶信息*/List<User> getUserByUsername(String username);}持久層接口對應配置文件(UserMapper.xml和RoleMapper.xml)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.demo.mapper.RoleMapper"><resultMap id="roleMap" type="com.example.demo.pojo.Role"><id column="id" property="id"></id><result column="name" property="name"></result></resultMap><select id="getRolesByUserId" resultMap="roleMap">select * from role r,user_role ur where r.id = ur.rid and ur.uid = #{userId}</select></mapper> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.demo.mapper.UserMapper"><resultMap id="userMap" type="com.example.demo.pojo.User"><id column="id" property="id"></id><result column="username" property="userName"></result><result column="password" property="passWord"></result><collection property="roles" ofType="com.example.demo.pojo.Role"><id property="id" column="rid"></id><result column="rname" property="name"></result></collection></resultMap><select id="getUserByUsername" resultMap="userMap">select * from user where username = #{username}</select> </mapper>源碼地址:SpringSecurity
總結
以上是生活随笔為你收集整理的SpringSecurity简单教程(源码开源免费提供)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA简单开发java和Spring
- 下一篇: SpringCloud教程