方法级别的Spring Security用法示例

除了身份验证之外, spring security还检查已登录用户的授权。登录后, 将根据用户的ROLE完成授权用户访问资源的操作。
在WebSecurityConfig类中创建用户时, 我们还可以指定用户的ROLE。
在方法上应用的安全性仅限于未授权用户, 并且仅允许真实用户。
让我们来看一个例子。首先通过提供详细信息创建一个Maven项目。

方法级别的Spring Security用法示例

文章图片
该项目最初看起来像这样:
方法级别的Spring Security用法示例

文章图片
Spring安全配置
现在, 配置应用程序以防止未经授权和未经身份验证的用户。它需要下面给出的四个Java文件, 创建一个包com.srcmini并将所有这些文件放在其中。
// AppConfig.java
此类用于在视图解析器的帮助下设置视图后缀和前缀。
package com.srcmini; 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.srcmini.controller.*" })public class AppConfig {@Beanpublic 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.srcmini; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MvcWebApplicationInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class< ?> [] getRootConfigClasses() {return new Class[] { WebSecurityConfig.class }; }@Overrideprotected Class< ?> [] getServletConfigClasses() {// TODO Auto-generated method stubreturn null; }@Overrideprotected String[] getServletMappings() {return new String[] { "/" }; }}

// SecurityWebApplicationInitializer.java
package com.srcmini; import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializerextends AbstractSecurityWebApplicationInitializer {}

// WebSecurityConfig.java
此类用于创建用户并设置其身份验证。当用户要访问应用程序时, 每次都需要登录。
package com.srcmini; 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.srcmini")@EnableGlobalMethodSecurity(prePostEnabled=true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic UserDetailsService userDetailsService() { // ensure the passwords are encoded properlyUserBuilder 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; } @Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/index", "/").permitAll().antMatchers("/admin", "/user").authenticated().and().formLogin().and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")); }}

控制者
创建一个控制器HomeController并将其放入com.srcmini.controller包中。
// HomeController.java
package com.srcmini.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; @Controllerpublic class HomeController {@RequestMapping(value="http://www.srcmini.com/", method=RequestMethod.GET)public String index() {return "index"; }@RequestMapping(value="http://www.srcmini.com/user", method=RequestMethod.GET)public String user() {return "admin"; }@RequestMapping(value="http://www.srcmini.com/admin", method=RequestMethod.GET)public String admin() {return "admin"; }// Only, a person having ADMIN role can access this method.@RequestMapping(value="http://www.srcmini.com/update", method=RequestMethod.GET) @ResponseBody@PreAuthorize("hasRole('ROLE_ADMIN')")public String update() {return "record updated "; }}

视图
创建以下视图(JSP页面)以为用户生成输出。将所有视图放入WEB-INF / views文件夹。
// index.jsp
< html> < head> < title> Home Page< /title> < /head> < body> Welcome to srcmini! < br> < br> Login as: < a href="http://www.srcmini.com/admin"> Admin< /a> < a href="http://www.srcmini.com/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="http://www.srcmini.com/logout" style="text-decoration: none; "> logout< /a> < br> < br> < a href="http://www.srcmini.com/update" style="text-decoration: none; "> Update Record< /a> < /body> < /html>

包依赖
以下是创建此项目所需的依赖项。
< 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.srcmini< /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>

项目结构
添加以上所有文件后, 我们的项目如下所示:
方法级别的Spring Security用法示例

文章图片
运行服务器
输出
方法级别的Spring Security用法示例

文章图片
首次以ADMIN身份登录
方法级别的Spring Security用法示例

文章图片
登录后,
方法级别的Spring Security用法示例

文章图片
单击更新记录, 然后看到记录已更新, 因为用户的角色是ADMIN。
方法级别的Spring Security用法示例

文章图片
用户登录
现在, 以用户身份登录。
方法级别的Spring Security用法示例

文章图片
方法级别的Spring Security用法示例

文章图片
【方法级别的Spring Security用法示例】现在, 单击更新记录, 查看服务器由于用户角色为USER而拒绝访问。
方法级别的Spring Security用法示例

文章图片

    推荐阅读