【问题标题】:Spring security authenticate user to enter adminSpring Security 验证用户进入 admin
【发布时间】:2016-06-26 05:17:00
【问题描述】:

我正在使用 Spring Security 对用户进行身份验证。

AdminController.java

@Controller
@Secured("ROLE_ADMIN")
public class AdminController {

     @RequestMapping("/list")
    public ModelAndView listProductController(@ModelAttribute("pForm") Product product, ModelMap model)
    {

         return new ModelAndView("list", model);
    }
}

我上面的代码,我希望只有管理员可以访问 url http://localhost/Pgga/list,但是即使没有登录,我也可以访问这个页面。

spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <global-method-security secured-annotations="enabled" />

    <!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin*" access="ROLE_ADMIN" />

        <!-- access denied page -->
        <access-denied-handler error-page="/403" />
        <form-login 
            login-page="/login"
            login-processing-url="/login.do"
            default-target-url="/index"
            authentication-failure-url="/login?error" 
            username-parameter="emailID"
            password-parameter="password" />
        <logout 
            logout-success-url="/login?logout"
            delete-cookies="JSESSIONID"
            invalidate-session="true" />
        <csrf/>
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="userAuthenticationProvider">
            <password-encoder hash="plaintext" />
        </authentication-provider>
    </authentication-manager>

</beans:beans>

如何只允许管理员进入管理区?

【问题讨论】:

  • 我认为,intercept-url pattern="/admin*" 不正确,你可以试试pattern="/**",因为这个pattern定义了URL路径
  • 出现错误:Failed to evaluate expression 'ROLE_ADMIN'
  • @HarshitShrivastava 你能把'ADMIN'代替'ROLE_ADMIN'吗?

标签: java spring spring-mvc spring-security


【解决方案1】:

使用 hasRole('admin') 或设置 use-expressions="false"....

【讨论】:

  • 现在页面被重定向到login并无限加载。
  • 如果用户未通过身份验证,则仅重定向到登录页面。请确保已完成身份验证。这可能会对您有所帮助stackoverflow.com/questions/28459446/…
  • 即使登录页面也被重定向到自身,所以它进入了无限循环。
【解决方案2】:

登录重定向到自己,因为你设置:

login-page="/login"

它会一直重定向到用户页面,因为 spring 知道 /login 它是登录页面,但无权使用它,所以添加这个:

<intercept-url pattern="/login" access="permitAll()" />

确保登录页面是允许的,并且可以向经过身份验证的用户授予访问权限或分配角色。

【讨论】:

    猜你喜欢
    • 2012-04-14
    • 2013-12-28
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2011-08-12
    • 2016-07-17
    • 2019-12-26
    相关资源
    最近更新 更多