社區連接:http://www.spring4all.com/article/428javascript
Spring Security 入門系列《Spring Security 動態權限修改》存在問題。 如下是改正後的代碼。css
pom.xmlhtml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>gs-securing-web</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.7.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency> <!-- bootstrap and jquery --> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.2.1</version> </dependency> <!-- testing --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Camden.SR5</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/libs-release</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories> </project>
啓動類java
package top.heliming.shiro.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; @SpringBootApplication @EnableGlobalMethodSecurity(prePostEnabled = true)//打開權限驗證 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
配置類jquery
package top.heliming.shiro.demo.config; /** * description: * * @author: he QQ: 905845006 * @email: 905845006@qq.com * @date: 2020/3/26 5:04 PM */ 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.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; // 使用註解方式配置SpringSecurity記住我配置時,開啓此註解 @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers( "/js/**", "/css/**", "/img/**", "/webjars/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .invalidateHttpSession(true) .clearAuthentication(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .permitAll() .and() .rememberMe() .key("unique-and-secret") .rememberMeCookieName("remember-me-cookie-name") .tokenValiditySeconds(24 * 60 * 60); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); //建立ADMIN角色 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("vip").password(new BCryptPasswordEncoder() .encode("123456")).roles("VIP"); //建立USER角色 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("demo").password(new BCryptPasswordEncoder() .encode("demo")).roles("USER"); } }
控制類web
package top.heliming.shiro.demo.controller; /** * description: * * @author: he QQ: 905845006 * @email: 905845006@qq.com * @date: 2020/3/26 5:08 PM */ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; @Controller public class HomeController { @GetMapping("/") public String greeting(){ return "index"; } @GetMapping("/login") public String login() { return "login"; } @GetMapping("/vip/test") //驗證不一樣角色的登陸權限 @PreAuthorize("hasRole('ROLE_VIP')")//只有是ADMIN權限的才能夠訪問該地址,使用該權限須要頭部引入打開權限驗證註解 @ResponseBody public String vipPath() { return "僅 ROLE_VIP 可看"; } @GetMapping("/vip") @ResponseBody public boolean updateToVIP() { // 獲得當前的認證信息 Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // 生成當前的全部受權 List<GrantedAuthority> updatedAuthorities = new ArrayList<>(auth.getAuthorities()); // 添加 ROLE_VIP 受權 updatedAuthorities.add(new SimpleGrantedAuthority("ROLE_VIP")); // 生成新的認證信息 Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), updatedAuthorities); // 重置認證信息 SecurityContextHolder.getContext().setAuthentication(newAuth); return true; } }
靜態文件spring
login.htmlapache
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}"/> <link rel="stylesheet" type="text/css" th:href="@{/css/main.css}"/> <title>Login</title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-body"> <div class="text-center"> <h3><i class="glyphicon glyphicon-lock" style="font-size:2em;"></i></h3> <h2 class="text-center">Login</h2> <div class="panel-body"> <div th:if="${param.error}"> <div class="alert alert-danger"> Invalid username or password. </div> </div> <div th:if="${param.logout}"> <div class="alert alert-info"> You have been logged out. </div> </div> <form th:action="@{/login}" method="post"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon">@</span> <input id="username" name="username" autofocus="autofocus" class="form-control" placeholder="Username"/> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"> <i class="glyphicon glyphicon-lock"></i> </span> <input id="password" name="password" class="form-control" placeholder="Password" type="password"/> </div> </div> <div class="form-group"> <label> <input id="remember-me" name="remember-me" type="checkbox"/> Remember me </label> </div> <div class="form-group"> <button type="submit" class="btn btn-success btn-block">Login</button> </div> </form> </div> </div> </div> </div> </div> </div> </div> <script type="text/javascript" th:src="@{/webjars/jquery/3.2.1/jquery.min.js/}"></script> <script type="text/javascript" th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script> </body> </html>
index.htmlbootstrap
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}"/> <link rel="stylesheet" type="text/css" th:href="@{/css/main.css}"/> <title>Registration</title> </head> <body> <div class="container"> <h1>Spring Security Remember Me Hashing Configuration Example</h1> <div sec:authorize="isRememberMe()"> The user: <span sec:authentication="name"></span> is logged in by "Remember Me Cookies". </div> <div sec:authorize="isFullyAuthenticated()"> The user: <span sec:authentication="name"></span> is logged in by "Username / Password". </div> </div> <footer> <div class="container"> <p> © Memorynotfound.com <span sec:authorize="isAuthenticated()" style="display: inline-block;"> | Logged user: <span sec:authentication="name"></span> | Roles: <span sec:authentication="principal.authorities"></span> | <a th:href="@{/logout}">Sign Out</a> </span> </p> </div> </footer> <script type="text/javascript" th:src="@{/webjars/jquery/3.2.1/jquery.min.js/}"></script> <script type="text/javascript" th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script> </body> </html>
測試cookie
輸入用戶:demo密碼:demo
登陸到主頁
訪問:http://localhost:8080/vip/test 提示403沒有權限 訪問:http://localhost:8080/vip 增長角色權限 訪問:http://localhost:8080/vip/test 返回 僅 ROLE_VIP 可看
修改後的地方:
-
啓動類開啓
@EnableGlobalMethodSecurity(prePostEnabled = true)//打開權限驗證
-
配置類
添加用戶 // auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); //建立ADMIN角色 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("vip").password(new BCryptPasswordEncoder() .encode("123456")).roles("VIP"); //建立USER角色 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("demo").password(new BCryptPasswordEncoder() .encode("demo")).roles("USER");
-
控制類
1. vipPath()方法修改註解@Secured("ROLE_VIP") 爲 //驗證不一樣角色的登陸權限 @PreAuthorize("hasRole('ROLE_VIP')")//只有是ADMIN權限的才能夠訪問該地址,使用該權限須要頭部引入打開權限驗證註解 增長註解@ResponseBody 2. updateToVIP()增長註解@ResponseBody