本人小菜雞 見諒
pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
config配置
package com.hexu.demo3.config;
import com.hexu.demo3.service.impl.UserDetailsServiceImpl;
import com.hexu.demo3.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
/**
* 安全框架
* @author 86176
*/
@EnableWebSecurity //開啟
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Resource
UserDetailsServiceImpl userDetailsServiceImpl;
/**
* 自定義MD5加密就這樣寫
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//資料庫是明文的話按下面就行了
//auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(new BCryptPasswordEncoder());
//資料庫不是明文 我用的是MD5加密
auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return MD5Util.getMD5((String) charSequence);
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(MD5Util.getMD5((String) charSequence));
}
});
}
//權限認證
@Override
protected void configure(HttpSecurity http) throws Exception {
//給頁面添加認證 不同級別進入不同的頁面 antMatchers(“頁面”) hasRole(“角色”)
http.authorizeRequests().antMatchers("/", "/lo").permitAll()
.antMatchers("/vip").hasAnyRole("VIP", "SSVIP", "SVIP")
.antMatchers("/svip").hasAnyRole("SVIP", "SSVIP")
.antMatchers("/ssvip").hasRole("SSVIP");
//沒有登錄回傳自帶的登錄頁面 loginPage(“自定義登陸頁面”)
http.formLogin().loginPage("/lo").loginProcessingUrl("/login").successForwardUrl("/").failureUrl("/lo").permitAll();
//啟動記住我功能 rememberMeParameter(“跟登陸頁面的記住我復選框name值一致”)
http.rememberMe().rememberMeParameter("remember");
//退出頁面 logoutSuccessUrl退出的地址
http.logout().logoutSuccessUrl("/").invalidateHttpSession(true).deleteCookies();
// 關閉 csrf 防護
http.csrf().disable();
}
}
//權限列名值要以 ROLE_開頭 hasRole(ROLE_后面的權限)
工具類
md5加密
package com.hexu.demo3.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
/**
* 1.MD5(message-digest algorithm 5)資訊摘要演算法,
* 它的長度一般是32位的16進制數字串(如81dc9bdb52d04dc20036dbd8313ed055)
* 2.由于系統密碼明文存盤容易被黑客盜取
* 3.應用:注冊時,將密碼進行md5加密,存到資料庫中,防止可以看到資料庫資料的人惡意篡改,
* 登錄時,將密碼進行md5加密,與存盤在資料庫中加密過的密碼進行比對
* 4.md5不可逆,即沒有對應的演算法,從產生的md5值逆向得到原始資料,
* 但是可以使用暴力破解,這里的破解并非把摘要還原成原始資料,如暴力列舉法,
*
*/
public final static String getMD5(String str){
try {
MessageDigest md = MessageDigest.getInstance("SHA");//創建具有指定演算法名稱的摘要
md.update(str.getBytes()); //使用指定的位元組陣列更新摘要
byte mdBytes[] = md.digest(); //進行哈希計算并回傳一個位元組陣列
String hash = "";
for(int i= 0;i<mdBytes.length;i++){ //回圈位元組陣列
int temp;
if(mdBytes[i]<0) //如果有小于0的位元組,則轉換為正數
temp =256+mdBytes[i];
else
temp=mdBytes[i];
if(temp<16)
hash+= "0";
hash+=Integer.toString(temp,16); //將位元組轉換為16進制后,轉換為字串
}
return hash;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
}
service
package com.hexu.demo3.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hexu.demo3.dao.UserDao;
import com.hexu.demo3.pojo.User;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.*;
/**
* 資料庫登錄類
* @author 86176
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Resource
UserDao userDao;
@Override
public UserDetails loadUserByUsername(String s) throws AuthenticationException {
QueryWrapper<User> queryWrap=new QueryWrapper<>();
queryWrap.eq("name",s);
User user = userDao.selectOne(queryWrap);
Assert.notNull(user,"賬號不存在");
//權限
List<GrantedAuthority> vip = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRake());
// 沒有用MD5加密就用這個 new BCryptPasswordEncoder().encode(user.getPass())
return new org.springframework.security.core.userdetails.User(user.getName(),user.getPass(),vip);
}
}
controller
package com.hexu.demo3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class hello {
@RequestMapping("/")
public String home() {
return "home";
}
@RequestMapping("/lo")
public String lo() {
return "login";
}
@RequestMapping("/vip")
public String vip() {
return "vip";
}
@RequestMapping("/svip")
public String svip() {
return "svip";
}
@RequestMapping("/ssvip")
public String ssvip() {
return "ssvip";
}
}
前端頁面
home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--沒有登陸顯示登陸-->
<div sec:authorize="isAnonymous()">
<a href="/lo">登錄</a>
</div>
<!--登陸的顯示退出 并且顯示當前的權限-->
<div sec:authorize="!isAnonymous()">
用戶名<span sec:authentication="name"></span>
角色<span sec:authentication="authorities"></span>
<a href="/logout">退出</a>
</div>
<!--級別訪問-->
<a sec:authorize="hasAnyRole('ROLE_VIP','ROLE_SSVIP','ROLE_SVIP')" href="/vip">vip通道</a>
<a sec:authorize="hasAnyRole('ROLE_SVIP','ROLE_SSVIP')" href="/svip">svip通道</a>
<a sec:authorize="hasAnyRole('ROLE_SSVIP')" href="/ssvip">大王vip通道</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login" method="post">
賬號 <input type="text" name="username">
密碼 <input type="password" name="password">
記住我 <input type="checkbox" name="remember">
<input type="submit" value="登錄">
</form>
</body>
</html>
ssvip.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
恭喜SSVIP進入
</body>
</html>
svip.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
恭喜SVIP進入
</body>
</html>
vip.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
恭喜VIP進入
</body>
</html>
結果
登陸頁面

svip用戶登陸

ssvip用戶登陸

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/400456.html
標籤:其他
