在这篇文章中,我们将为您详细介绍如何在SpringSecurityTaglib中不提及hasRole的内容,并且讨论关于'ROLE_ADMIN'的相关问题。此外,我们还会涉及一些关于springboo
在这篇文章中,我们将为您详细介绍如何在Spring Security Taglib中不提及hasRole的内容,并且讨论关于'ROLE_ADMIN'的相关问题。此外,我们还会涉及一些关于spring boot 1.5.10.RELEASE ,spring boot admin 1.5.7 添加 security、Spring Security / Spring Boot-如何为用户设置ROLES、Spring Security hasRole()无法正常工作、Spring Security jsptaglibs 在Velocity模版 需要怎么写?的知识,以帮助您更全面地了解这个主题。
本文目录一览:- 如何在Spring Security Taglib中不提及hasRole('ROLE_ADMIN')(spring security不拦截)
- spring boot 1.5.10.RELEASE ,spring boot admin 1.5.7 添加 security
- Spring Security / Spring Boot-如何为用户设置ROLES
- Spring Security hasRole()无法正常工作
- Spring Security jsptaglibs 在Velocity模版 需要怎么写?
如何在Spring Security Taglib中不提及hasRole('ROLE_ADMIN')(spring security不拦截)
我将如何使用Spring Security Taglib编写以下条件?
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %><sec:authorize access="not of hasRole(''ROLE_ADMIN'')"> <div> show these for only non admins </div></sec:authorize>
答案1
小编典典<sec:authorize access="!hasRole(''ROLE_ADMIN'')"> <div> show these for only non admins </div></sec:authorize>
spring boot 1.5.10.RELEASE ,spring boot admin 1.5.7 添加 security
生产环境的客户端actuator最好是加上security校验,不然配置信息不登录就能直接获取到
server端配置,参考官方 文档,https://codecentric.github.io/spring-boot-admin/1.5.7/#getting-started
代码参见,码云,https://gitee.com/xiongjinpeng/spring-boot-admin
pom.xml
<?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>com.xx</groupId>
<artifactId>spring-boot-admin</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>spring-boot-admin</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-boot-admin.version>1.5.7</spring-boot-admin.version>
</properties>
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-login</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
<finalName>${project.name}</finalName>
</configuration>
</plugin>
</plugins>
</build>
</project>
SecurityConfig.java,官方的配置
import org.springframework.context.annotation.Configuration;
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;
/**
* 基于安全认证的spring boot admin
*
* @author niugang
*
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Page with login form is served as /login.html and does a POST on /login
http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll();
// The UI does a POST on /logout on logout
http.logout().logoutUrl("/logout");
// The ui currently doesn''t support csrf
http.csrf().disable();
// Requests for the login page and the static assets are allowed
//允许登录页面和静态资源的请求
http.authorizeRequests()
.antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**")
.permitAll();
// ... and any other request needs to be authorized
//这点重要:所有请求都需要认证
http.authorizeRequests().antMatchers("/**").authenticated();
// Enable so that the clients can authenticate via HTTP basic for registering
http.httpBasic();
}
}
application.properties
server.port=8011
#关闭原始的spring security 认证,不关闭的话,浏览器打开就会跳出弹出框
security.basic.enabled=false
#spring boot actuator某些端点的访问时需要权限的
management.security.enabled=false
#spring boot default user.name=''user''
security.user.name=admin
#spring boot dafault user.password 在项目启动时打印在控制台中
security.user.password=123456
client端,客户端代码,
maven添加
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
SecuritySecureConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
//拦截所有endpoint,拥有ACTUATOR_ADMIN角色可访问,否则需登录
//静态文件允许访问
.antMatchers("/css/**", "/images/**","/js/**","/webjars/**","/**/favicon.ico").permitAll()
//根路径允许访问
.antMatchers("/").permitAll()
//所有请求路径可以访问
.antMatchers("/**").permitAll()
.and().httpBasic();
}
}
application.properties
spring.application.name=client
#要注册的Spring Boot Admin Server的URL
spring.boot.admin.url=http://localhost:8011
#从Spring Boot 1.5.x开始,默认情况下所有端点都是安全的。 为简洁起见,我们暂时禁用了安全性。 查看有关如何处理安全端点的安全性部分。
#management.security.enabled=false
#注册到server端用
spring.boot.admin.client.metadata.user.name=admin
spring.boot.admin.client.metadata.user.password=123456
#如果保护/api/applications端点,请不要忘记使用spring.boot.admin.username和spring.boot.admin.password在SBA客户端上配置用户名和密码【否则你的client端信息注册不到server端上】
#注册到server端用
spring.boot.admin.username=admin
spring.boot.admin.password=123456
#配置很重要,server端主动获取信息会用到
security.user.name=admin
security.user.password=123456
最新测试,还可以精简一下去掉代码
.antMatchers(
"/info",
"/info.json",
"/health",
"/health.json",
"/metrics",
"/metrics.json",
"/dump",
"/dump.json",
"/metrics/*",
"/beans",
"/beans.json",
"/configprops",
"/configprops.json",
"/auditevents",
"/auditevents.json",
"/heapdump",
"/heapdump.json",
"/trace",
"/trace.json",
"/env/*",
"/env",
"/env.json",
"/loggers/*",
"/loggers",
"/loggers.json",
"/mappings",
"/mappings.json",
"/jolokia/**"
).hasRole("ACTUATOR_ADMIN")
和
management.security.roles=ACTUATOR_ADMIN
去掉这2个,也可以达到效果。
Spring Security / Spring Boot-如何为用户设置ROLES
使用安全性登录时,无法使用该request.isUserInRole()
方法。我认为没有设置用户的角色。
这是我的安全配置:
@Configuration@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled=true)@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate DataSource dataSource;@Autowiredprivate UserDetailsServiceImplementation userDetailsService;@Overrideprotected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/signup").permitAll() .antMatchers("/").permitAll() //.antMatchers("/first").hasAuthority("Service_Center") .antMatchers("/login").permitAll() .anyRequest().fullyAuthenticated() .and().formLogin() .loginPage("/login") .usernameParameter("email") .passwordParameter("password") .defaultSuccessUrl("/default") .failureUrl("/login?error").permitAll() .and().logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .deleteCookies("JSESSIONID") .invalidateHttpSession(true).permitAll();}@Autowiredpublic void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService);}}
这是我的User
实体:
@Entity @Table(name="user") public class User implements Serializable{/** * */private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.AUTO)@Column(name="user_id")private Long userID;@Column(name="email_address", nullable = false, unique = true)private String emailAddress;@Column(name="password")private String password;@Column(name = "role", nullable = false)@Enumerated(EnumType.STRING)private Role role;public User() { super();}public User(String emailAddress, String password) { this.emailAddress = emailAddress; this.password = password;}public Long getUserID() { return userID;}public void setUserID(Long userID) { this.userID = userID;}public String getEmailAddress() { return emailAddress;}public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress;}public String getPassword() { return password;}public void setPassword(String password) { this.password = password;}public Role getRole() { return role;}public void setRole(Role role) { this.role = role;}@Overridepublic String toString() { return "User [userID=" + userID + ", emailAddress=" + emailAddress + ", password=" + password + ", role=" + role + "]";}public UserDetails toCurrentUserDetails() { return CurrentUserDetails.create(this);}}
这是我的枚举Role
:
public enum Role {Fleet_Company, Service_Center, Admin}
这是我的UserDetailsServiceImplementation
:
@Componentpublic class UserDetailsServiceImplementation implements UserDetailsService {@Autowiredprivate UserRepository userRepository;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if ( username == null || username.isEmpty() ){ throw new UsernameNotFoundException("username is empty"); } User foundUser = userRepository.findByEmailAddress(username); if( foundUser != null ){ System.out.println("FOUND"); return foundUser.toCurrentUserDetails(); } throw new UsernameNotFoundException( username + "is not found");}}
这是实现的类UserDetails
:
public class CurrentUserDetails implements UserDetails {private Long userID;private String emailAddress;private String password;private Role role;public CurrentUserDetails(Long userID, String emailAddress, String password, Role role) { super(); this.userID = userID; this.emailAddress = emailAddress; this.password = password; this.role = role;} /* public static UserDetails create(Users entity) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for(Authorities auth: entity.getAuthorities()){ authorities.add(new SimpleGrantedAuthority(auth.getId().getAuthority())); } return new MyUserDetail(entity.getUserId(), entity.getLoginId(), entity.getPassword(), entity.getDisplayName(), authorities);}*/public Long getUserID(){ return this.userID;}public Role getRole(){ return this.role;}@Overridepublic String getPassword() { return this.password;}public String getEmailAddress() { return this.emailAddress;}@Overridepublic boolean isAccountNonExpired() { return true;}@Overridepublic boolean isAccountNonLocked() { return true;}@Overridepublic boolean isCredentialsNonExpired() { return true;}@Overridepublic boolean isEnabled() { return true;}public static UserDetails create(User entity) { System.out.println(entity.getUserID()+ entity.getEmailAddress()+ entity.getPassword()+ entity.getRole()); return new CurrentUserDetails(entity.getUserID(), entity.getEmailAddress(), entity.getPassword(), entity.getRole());}@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() { // TODO Auto-generated method stub return null;}@Overridepublic String getUsername() { // TODO Auto-generated method stub return null;}}
因此,基本上,我们可以看到我的MySQL数据库上只有一个表,它有四列,其中一列是“角色”。
但是就像我说的那样,当我使用时request.isUserInRole("Service_Center")
,它返回FALSE。而且.antMatchers("/first").hasAuthority("Service_Center")
也不起作用。
答案1
小编典典创建UserDetails时,您应该自己填写角色的内容:
public class SecurityUser implements UserDetails{ String ROLE_PREFIX = "ROLE_"; String userName; String password; String role; public SecurityUser(String username, String password, String role){ this.userName = username; this.password = password; this.role = role; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); list.add(new SimpleGrantedAuthority(ROLE_PREFIX + role)); return list; }
基本上,您需要做的是重写方法:getAuthorities
,然后将角色字段的内容填充到GrantedAuthority
列表中。
Spring Security hasRole()无法正常工作
我在使用Spring Security &&
Thymeleaf时遇到问题,特别是在尝试使用hasRole表达式时。“ admin”用户的角色为“ ADMIN”,但hasRole(''ADMIN'')
无论如何我都会解析为false
我的html:
1.<div sec:authentication="name"></div> <!-- works fine -->2.<div sec:authentication="principal.authorities"></div> <!-- works fine -->3.<div sec:authorize="isAuthenticated()" >true</div> <!-- works fine -->4.<span th:text="${#authorization.expression(''isAuthenticated()'')}"></span> <!-- works fine -->5.<div th:text="${#vars.role_admin}"></div> <!--Works fine -->6.<div sec:authorize="${hasRole(''ADMIN'')}" > IS ADMIN </div> <!-- Doesnt work -->7.<div sec:authorize="${hasRole(#vars.role_admin)}" > IS ADMIN </div> <!-- Doesnt work -->8.<div th:text="${#authorization.expression(''hasRole(''''ADMIN'''')'')} "></div> <!-- Doesnt work -->9.<div th:text="${#authorization.expression(''hasRole(#vars.role_admin)'')}"></div> <!-- Doesnt work -->
结果是:
1.admin2.[ADMIN]3.true4.true5.ADMIN6."prints nothing because hasRole(''ADMIN'') resolves to false"7."prints nothing because hasRole(#vars.role_admin) resolves to false"8.false9.false
我在security.xml文件中启用了 use-expressions
<security:http auto-config="true" use-expressions="true">
并且在我的配置中还包含了SpringSecurityDialect
<bean id="templateEngine"> <property name="templateResolver" ref="templateResolver" /> <property name="additionalDialects"> <set> <bean/> </set> </property> </bean>
我的pom.xml文件中的所有必需依赖项
<!--Spring security--> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.0.1.RELEASE</version> </dependency> <!--Thymeleaf Spring Security--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>2.1.2.RELEASE</version> <scope>compile</scope> </dependency>
角色.java
@Entity@Table(name = "roles") public class Role implements Serializable { @Id @Enumerated(EnumType.STRING) private RoleType name; //... getters, setters }
角色类型
public enum RoleType { ADMIN }
并User
拥有一套Role
小号
为什么hasRole()
不工作?
感谢您的帮助,谢谢
解决方法
th:if="${#strings.contains(#authentication.principal.authorities,''ADMIN'')}"
答案1
小编典典尝试在HTML标签内使用hasAuthority
代替hasRole
。
sec:authorize="hasAuthority(''ADMIN'')"
Spring Security jsptaglibs 在Velocity模版 需要怎么写?
Spring Security jsptaglibs 在Velocity模版 需要怎么写?我们今天的关于如何在Spring Security Taglib中不提及hasRole和'ROLE_ADMIN'的分享就到这里,谢谢您的阅读,如果想了解更多关于spring boot 1.5.10.RELEASE ,spring boot admin 1.5.7 添加 security、Spring Security / Spring Boot-如何为用户设置ROLES、Spring Security hasRole()无法正常工作、Spring Security jsptaglibs 在Velocity模版 需要怎么写?的相关信息,可以在本站进行搜索。
本文标签: