除了身份驗證,Spring Security還檢查登錄用戶的授權(quán)。登錄后,將根據(jù)用戶的ROLE完成授權(quán)用戶訪問資源的操作。
在WebSecurityConfig類中創(chuàng)建用戶時,我們也可以指定用戶的ROLE。
應(yīng)用于方法的安全性僅限于未經(jīng)授權(quán)的用戶,并且僅允許真實用戶。
讓我們看一個示例。首先,通過提供詳細信息創(chuàng)建一個Maven項目。
該項目最初看起來像這樣:
現(xiàn)在,配置應(yīng)用程序以防止未經(jīng)授權(quán)和未經(jīng)身份驗證的用戶。它需要下面給出的四個Java文件,創(chuàng)建一個包com.nhooo并將其放在其中。
//AppConfig.java
此類用于在視圖解析器的幫助下設(shè)置視圖后綴和前綴。
package com.nhooo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan({ "com.nhooo.controller.*" })
public class AppConfig {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
//MvcWebApplicationInitializer.java.java
package com.nhooo;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MvcWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebSecurityConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TOdo Auto-generated method stub
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
//SecurityWebApplicationInitializer.java
package com.nhooo;
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
//WebSecurityConfig.java
此類用于創(chuàng)建用戶并設(shè)置其身份驗證。每當用戶要訪問該應(yīng)用程序時,都需要登錄。
package com.nhooo;
import org.springframework.context.annotation.*;
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.*;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
@ComponentScan("com.nhooo")
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
// ensure the passwords are encoded properly
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("irfan").password("user123").roles("USER").build());
manager.createUser(users.username("admin").password("admin123").roles("ADMIN").build());
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().
antMatchers("/index","/").permitAll()
.antMatchers("/admin","/user").authenticated()
.and()
.formLogin()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
}
創(chuàng)建控制器HomeController并放入 com.nhooo.controller 包中。
//HomeController.java
package com.nhooo.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value="/user", method=RequestMethod.GET)
public String user() {
return "admin";
}
@RequestMapping(value="/admin", method=RequestMethod.GET)
public String admin() {
return "admin";
}
// Only, a person having ADMIN role can access this method.
@RequestMapping(value="/update", method=RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String update() {
return "record updated ";
}
}
創(chuàng)建以下視圖(JSP頁面)以為用戶生成輸出。將所有視圖放入 WEB-INF/views 文件夾。
//index.jsp
<html> <head> <title>Home Page</title> </head> <body> Welcome to Nhooo! <br> <br> Login as: <a href="admin">Admin</a> <a href="user">User</a> </body> </html>
//admin.jsp
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Home Page</title> </head> <body> <span style="color: green">Login Successful!</span> ? <a href="logout" style="text-decoration: none;">logout</a> <br> <br> <a href="update" style="text-decoration: none;">Update Record</a> </body> </html>
以下是創(chuàng)建此項目所需的依賴項。
<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>com.nhooo</groupId> <artifactId>springmethod</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.0.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-framework-bom --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
添加上述所有文件后,我們的項目如下所示:
輸出:
首次以ADMIN身份登錄
登錄后,
點擊 更新記錄,然后查看記錄是否已更新,因為用戶的角色是ADMIN。
現(xiàn)在,以用戶身份登錄。

現(xiàn)在,單擊 更新記錄,由于用戶角色為USER,因此服務(wù)器拒絕訪問。