碼雲地址:https://gitee.com/huatao1994/springbootSecurity/tree/mastercss
package cn.**.security.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @ProjectName: springbootSecurity * @Package: cn.**.security.controller * @Author: huat * @Date: 2019/12/12 14:56 * @Version: 1.0 */ @RestController public class UserController { //@Secured("ROLE_ADMIN")//security權限註解 //@RolesAllowed("ROLE_ADMIN") //jsr250註解 //@PreAuthorize("hasRole('ROLE_ADMIN')")//spring的註解 @RequestMapping("/login") public String login(String username,String password){ //獲取登錄的用戶名 String username1= SecurityContextHolder.getContext().getAuthentication().getName(); System.out.println(username); return "index"; } @RequestMapping("test") public String test(){ return "你好這裏是test頁面"; } }
package cn.**.security.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @ProjectName: springbootSecurity * @Package: cn.**.security.controller * @Author: huat * @Date: 2019/12/16 15:16 * @Version: 1.0 */ @Controller public class IntoController { @RequestMapping("intoTest") public String intoTest(){ return "/test"; } @RequestMapping("intoIndex") public String intoIndex(){ return "index"; } @RequestMapping("intoFail") public String intoFail(){ return "fail"; } @RequestMapping("intoLogin") public String intoLogin(){ return "login"; } @RequestMapping("dologin") public String dologin(){ return "index"; } }
package cn.**.security.util; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import java.security.MessageDigest; /** * @ProjectName: springbootSecurity * @Package: cn.**.security.util * @Author: huat * @Date: 2019/12/13 17:14 * @Version: 1.0 * 自定義加密類 */ @Component public class MyPasswordEncoder implements PasswordEncoder { private static final String SALT = "jzd,.,."; /** * 加密 * @param charSequence 須要加密的密碼 * @return */ @Override public String encode(CharSequence charSequence) { charSequence = charSequence + SALT; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new RuntimeException(e); } char[] charArray = charSequence.toString().toCharArray(); byte[] byteArray = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i]; byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } /** * 判斷加密後的密碼是否一致 * @param charSequence 須要加密的密碼 * @param password 數據庫中加密後的密碼,權限框架會直接傳入 * @return */ @Override public boolean matches(CharSequence charSequence, String password) { String pwd=encode(charSequence); if(pwd.equals(password)){ return true; } return false; } public static void main(String[] args) { MyPasswordEncoder passwordEncoder=new MyPasswordEncoder(); System.out.println(passwordEncoder.encode("123456")); } }
package cn.**.security.util; 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.method.configuration.EnableGlobalMethodSecurity; 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; /** * @ProjectName: springbootSecurity * @Package: cn.**.security.util * @Author: huat * @Date: 2019/12/14 8:06 * @Version: 1.0 */ /** * 開啓security註解支持 * @EnableWebSecurity * (securedEnabled=true) 開啓@Secured 註解過濾權限 * (jsr250Enabled=true)開啓@RolesAllowed 註解過濾權限 * (prePostEnabled=true) 使用表達式時間方法級別的安全性 4個註解可用 * @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true) */ @Configuration @EnableWebSecurity //@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true) public class SpringSercurityConfig extends WebSecurityConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; /** * 將帳號密碼設置在內存當中 * @param auth * @throws Exception */ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { //從內存中獲取帳號密碼 auth.inMemoryAuthentication() //設置帳號 .withUser("admin") //設置,密碼{noop}表明明文 .password(passwordEncoder.encode("1")) //配置類中加角色不能有前綴 .roles("USER"); } @Override public void configure(HttpSecurity http) throws Exception { //釋放靜態資源,指定資源攔截規則, // 指定自定義認證頁面,指定退出認證配置,csrf(跨域僞造請求)配置 http.authorizeRequests() .antMatchers("intoLogin","login.jsp","/css/**","fail.jsp","/intoIndex","/index.jsp").permitAll()//釋放這些資源,容許匿名訪問 .antMatchers("/**").hasAnyRole("ADMIN","USER") .anyRequest().authenticated()//其餘資源須要認證 .and() .formLogin() .loginPage("/intoLogin")//登錄頁請求的接口 .loginProcessingUrl("/dologin")//登錄地址,由springSecurity提供 .successForwardUrl("/intoTest")//登錄成功 .failureForwardUrl("/intoFail")//登陸失敗 .permitAll()//指定全部資源釋放 .and() .logout()//登出 .logoutUrl("/logout")//指定登出路徑 .logoutSuccessUrl("/intoLogin")//登出成功後跳轉的url .invalidateHttpSession(true)//是否清空session .permitAll() .and() .csrf() .disable();//關閉csrf(跨域僞造請求) } }
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/12/16 Time: 15:10 To change this template use File | Settings | File Templates. --%> <%@ page isELIgnored="false" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <html> <head> <title>測試</title> </head> <body> ceshi <security:authentication property="name"></security:authentication> <!--動態顯示 知足USER角色才能看到--> <security:authorize access="hasRole('USER')"> 能夠看到 </security:authorize> </body> </html>
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/12/16 Time: 15:10 To change this template use File | Settings | File Templates. --%> <%@ page isELIgnored="false" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <html> <body> <form method="post" action="/dologin"> name:<input name="username"> password:<input name="password"> <input type="submit"> </form> </body> </html>