Аннотация Spring Security Control Access

Я работаю с Spring Security (3.2.5.RELEASE) и хочу заблокировать доступ пользователей (ROLE_USER) к этой странице ниже и предоставить только администратору (ROLE_ADMIN).

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

Пожалуйста, не могли бы вы мне помочь?

Это схема базы данных:

USE [PLADW]
GO

/****** Object:  Table [LADW].[WUI_USERS]    Script Date: 21/08/2014 14:16:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [LADW].[WUI_USERS](
    [USERNAME] [varchar](50) NOT NULL,
    [PASSWORD] [varchar](50) NOT NULL,
    [ENABLED] [bit] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [USERNAME] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [LADW].[WUI_USERS] ADD  DEFAULT ((1)) FOR [ENABLED]
GO

а также

USE [PLADW]
GO

/****** Object:  Table [LADW].[WUI_AUTHORITIES]    Script Date: 21/08/2014 14:17:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [LADW].[WUI_AUTHORITIES](
    [USERNAME] [varchar](50) NOT NULL,
    [AUTHORITY] [varchar](50) NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [LADW].[WUI_AUTHORITIES]  WITH CHECK ADD  CONSTRAINT [FK_AUTHORITIES_USERS] FOREIGN KEY([USERNAME])
REFERENCES [LADW].[WUI_USERS] ([USERNAME])
GO

ALTER TABLE [LADW].[WUI_AUTHORITIES] CHECK CONSTRAINT [FK_AUTHORITIES_USERS]
GO

домашняя страница.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ page language="java" session="true" %>

<html lang="en-us">
<head>
<title>${title}</title>
</head>

<body>

    <h1><spring:message code="label.title" /></h1>
    <h3>${pageContext.response.locale}</h3>
    <h4>Language : </h4><a href="?lang=en_US">English</a> | 
    <a href="?lang=pt_BR">Portuguese Brazillian</a> | 
    <a href="?lang=es_ES">Spanish (Spain)</a>

    <!-- Logout form -->
    <h1>This is secured!</h1>
    <p>Hello <b><c:out value="${pageContext.request.remoteUser}" /></b></p>
    <c:url var="logoutUrl" value="/logout" />
    <form action="${logoutUrl}" method="post">
        <input type="submit" value="Log out" />
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    </form>

</body>

</html>

SecurityConfig

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;

@Configuration
@EnableWebSecurity
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        String query_uid = "select username, password, enabled from ladw.wui_users where username = ?";
        String query_auth = "select username, authority from ladw.wui_authorities where username = ?";

        auth
            .jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery(query_uid)
                .authoritiesByUsernameQuery(query_auth);    
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
        .sessionManagement()
            .maximumSessions(1)
            .maxSessionsPreventsLogin(true)
            .expiredUrl("/login?logout");

        http
        .authorizeRequests()
            .antMatchers("/resources/**").permitAll() 
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()                                    
            .permitAll();

        http
        .authorizeRequests()
            .antMatchers("/", "/homepage")
            .access("hasRole('ROLE_ADMIN')")
            .and()
        .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and()
        .logout()
            .logoutSuccessUrl("/login?logout")
            .and()
        .exceptionHandling().accessDeniedPage("/403")
            .and()
        .csrf();

    }
}

Контроллер

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @RequestMapping(value = { "/", "/homepage" }, method = RequestMethod.GET)
    public ModelAndView homePage() {

        ModelAndView mv = new ModelAndView();
        mv.addObject("title", "Homepage");
        mv.setViewName("homepage");
        return mv;
    }
}

person gcfabri    schedule 21.08.2014    source источник


Ответы (1)


Вы должны иметь возможность заменить несколько конфигураций безопасности http одной, подобной этой.

http
       .authorizeRequests()
       .antMatchers("/","/homepage").access("hasRole('ROLE_ADMIN')")
       .antMatchers("/resources/**").permitAll() 
       .anyRequest().hasRole("USER")
       .and()
       .formLogin()
       .loginPage("/login")
       .permitAll()
       .and()
       .logout()                                    
       .permitAll();

Если другие конфигурации, которые отличаются между вашими конфигурациями http, имеют значение:

failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")

попробуйте разделить несколько конфигураций безопасности http на разные классы, как вы можете видеть здесь: https://github.com/spring-projects/spring-security/blob/master/config/src/test/groovy/org/springframework/security/config/annotation/web/SampleWebSecurityConfigurerAdapterTests.groovy#L277

person Adrian Lopez    schedule 21.08.2014