Библиотека тегов безопасности Spring sec: URL-адрес авторизации не работает

В моем проекте весенней загрузки я использую библиотеки тегов безопасности Spring. Когда я вошел в систему как идентификатор пользователя с ролью ROLE_USER, в соответствии с моей конфигурацией ниже не должна отображаться область ADMIN.

<sec:authorize  url = "/admin/**">
        <p>This is shown who has a role ADMIN</p>
    </sec:authorize>

эта часть.

но это не работает.

<%@ page language = "java" contentType = "text/html; charset=UTF-8" pageEncoding = "UTF-8"%>
<%@ taglib prefix = "sec" uri = "http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>Welcome Home <sec:authentication property = "name"/></h2>
    <h3>roles : <sec:authentication property = "principal.authorities"/></h2>

    <sec:authorize access = "hasRole('ADMIN')">
        <p>This is shown who has a role ADMIN</p>
    </sec:authorize>

    <sec:authorize access = "hasRole('USER')">
        <p>This is shown who has a role USER</p>
    </sec:authorize>

    <sec:authorize access = "hasRole('TESTER')">
        <p>This is shown who has a role TESTER</p>
    </sec:authorize>

    <sec:authorize url = "/admin/**">
        <p>This is shown whom can access to /admin/**</p>
    </sec:authorize>

    <sec:authorize url = "/user/**">
        <p>This is shown whom can access to /user/**</p>
    </sec:authorize>

    <sec:authorize url = "/tester/**">
        <p>This is shown whom can access to /tester/**</p>
    </sec:authorize>

    <form action = "/logout" method = "post">
        <input type = "submit" value = "Sign Out"/>
    </form>

</body>
</html>

[просмотр] [1]

Я попробовал все ответы на эту проблему в stackoverflow, но до сих пор не могу это исправить. Уже более 2 недель пытались решить эту проблему. когда я тестировал тимелеаф с теми же конфигурациями java, он работал. но не работает с jsp.

вот мои настройки Конфигурация безопасности Java Spring

Пожалуйста, помогите мне решить эту проблему.

 @Configuration
    @EnableWebSecurity
    public class WebSecurity {

        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .expressionHandler(expressionHandler())
                    .antMatchers("/", "/home", "/test").permitAll()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .antMatchers("/user/**").hasAnyRole("USER")
                    .antMatchers("/tester/**").hasAnyRole("TESTER")
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();

        }

        @Bean
        public RoleHierarchyImpl roleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
            String hierarchy  = "ROLE_ADMIN > ROLE_USER and ROLE_USER > ROLE_TESTER";
            roleHierarchy.setHierarchy(hierarchy);
         return roleHierarchy;
        }


        // create two users, admin and user
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

            auth.inMemoryAuthentication()
                    .withUser("user").password("{noop}password").roles("USER")
                    .and()
                    .withUser("tester").password("{noop}tester").roles("TESTER")
                    .and()
                    .withUser("admin").password("{noop}admin").roles("ADMIN");
        }


        private SecurityExpressionHandler<FilterInvocation> expressionHandler() {
            DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
            defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy());
            return defaultWebSecurityExpressionHandler;
        }

    }

build.gradle

buildscript {
    ext {
        springBootVersion = '2.0.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.bulky'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // tag::security[]
    compile("org.springframework.boot:spring-boot-starter-security")
    compile 'org.springframework.security:spring-security-taglibs:5.0.5.RELEASE'
    // end::security[]
    compile 'javax.servlet:jstl:1.2'
    compile 'org.apache.tomcat.embed:tomcat-embed-jasper:9.0.0.M18'
}

пс: извините за плохой английский

0
0
1 407
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Все ваши настройки безопасности верны, кроме класса WebSecurity, который не расширяет WebSecurityConfigurerAdapter. Я думаю, вам нужно сначала расширить этот класс, чтобы переопределить метод настройки:

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
   //Your Code here
  }

Другие вопросы по теме