在Spring中添加管理部分 [英] Adding an admin section in Spring

查看:85
本文介绍了在Spring中添加管理部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Web项目,需要一个管理部分.我以为这部分会很容易,并且会遇到安全性问题,但是我什至无法指向/admin/部分.

I have a Spring web project, which needs an admin section. I assumed this part would be easy and that I would have issues with security, but I can't even point to a /admin/ section.

在我的dispatcher-servelet.xml中,有以下内容可将JSP文件映射到控制器:

I have the following in my dispatcher-servelet.xml to map JSP files to controllers:

<context:component-scan base-package="controller"/>
<context:component-scan base-package="controller.admin"/>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

/WEB-INF/jsp/中现在有一个标记为"admin"的文件夹,并且我有adminindex.jsp.我在web.xml中也有以下内容

There is now a folder labelled "admin" in /WEB-INF/jsp/ and there I have adminindex.jsp. I also have the following in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
    <security-constraint>
        <display-name>Constraint1</display-name>
    </security-constraint>
    <security-constraint>
        <display-name>admin pages</display-name>
        <web-resource-collection>
            <web-resource-name>Administration Pages</web-resource-name>
            <description/>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>eCommerceAdmin</role-name>
        </auth-constraint>
        <!--  <user-data-constraint>
            <description/>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>-->
    </security-constraint>
</web-app>

当我尝试访问

localhost:8080/NewWebsite/admin/adminindex.htm

localhost:8080/NewWebsite/admin/adminindex.htm

,我得到

对请求资源的访问已被拒绝

Access to the requested resource has been denied

INFO:ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@44d1bd08')

INFO: ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@44d1bd08')

我可以轻松访问

localhost:8080/NewWebsite/index.htm,我也想对admin文件夹进行自动重定向,就像与根文件夹一样.即

localhost:8080/NewWebsite/index.htm, and I would also like to have an auto redirect for the admin folder like it is with the root folder. I.E going to

localhost:8080/NewWebsite/指向index.htm.

localhost:8080/NewWebsite/ directs to index.htm.

任何帮助都会很棒.

推荐答案

首先需要验证用户吗?否则,您的应用程序将如何识别ADMIN正在尝试访问的用户或普通USER?
在执行此操作之前,请从 web.xml
中删除security-constraint 因此,在您的应用中添加spring身份验证.
首先创建一个pojo类,以包含一个应实现org.springframework.security.core.userdetails.UserDetailsGrantedAuthority列表.下面是一个示例:

FIrst you need to validate the user?isn't it? Otherwise how your application would recognise wheter ADMIN is trying to access or normal USER?
Before you do this remove security-constraint from your web.xml
So Add spring authentication in your app.
First Create a pojo class to have a list of GrantedAuthority which should implement org.springframework.security.core.userdetails.UserDetails . Below is a sample:

public class YourPojo implements UserDetails{


    /** The authorities. */
    //This collection will have eCommerceAdmin
    public Collection<GrantedAuthority> authorities;

    /** The username. */
    public String username;

    /** The account non expired. */
    public boolean accountNonExpired;

    /** The credentials non expired. */
    public boolean credentialsNonExpired;

    /** The enabled. */
    public boolean enabled;

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -2342376103893073629L;

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#getAuthorities()
     */
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return authorities;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#getPassword()
     */
    @Override
    public String getPassword() {
        return null;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#getUsername()
     */
    @Override
    public String getUsername() {
        return username;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired()
     */
    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked()
     */
    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isCredentialsNonExpired()
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetails#isEnabled()
     */
    @Override
    public boolean isEnabled() {
        return enabled;
    }


    /**
     * Sets the authorities.
     *
     * @param authorities the new authorities
     */
    public void setAuthorities(Collection<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    /**
     * Sets the username.
     *
     * @param username the new username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * Sets the account non expired.
     *
     * @param accountNonExpired the new account non expired
     */
    public void setAccountNonExpired(boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    /**
     * Sets the account non locked.
     *
     * @param accountNonLocked the new account non locked
     */
    public void setAccountNonLocked(boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    /**
     * Sets the credentials non expired.
     *
     * @param credentialsNonExpired the new credentials non expired
     */
    public void setCredentialsNonExpired(boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }

    /**
     * Sets the enabled.
     *
     * @param enabled the new enabled
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

}

下面是您需要的HTTP标记.

Below is the HTTP tag that you require.

<!-- to use Spring security tags -->
    <bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />
<http pattern="/login*" security="none"/>
<http pattern="/static/**" security="none"/>        
<http auto-config="false">      
        <intercept-url pattern="/admin/**" access="eCommerceAdmin" />
        <form-login login-page="/login" default-target-url="/welcome"
            authentication-failure-url="/loginfailed" />
        <logout logout-success-url="/logout" />     

        <session-management>
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>           
    </http>

现在定义您的身份验证提供程序.

Now define your authentication provider.

<bean id="customeAuthProvider" class="your.auth.provider.class">
  </bean>

   <authentication-manager >        
        <authentication-provider ref="customeAuthProvider" ></authentication-provider>
  </authentication-manager>

customeAuthProvider应该实现org.springframework.security.authentication.AuthenticationProvider.

@Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication;
        String username = userToken.getName();
        String password = (String) authentication.getCredentials();
          //Do whatevr you want with the credentials
         //Then populate the authorities for this credential
         YourPojo user=new YourPojo ();
         user.setUserName("add username");
        //set other details
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
        //if user is admin add the below line
        GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl("eCommerceAdmin");
       //Add other authorities as applicable like 'user' etc.
       user.setAuthorities(grantedAuthorityList);
       return new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities());

您可以按如下方式在web.xml中引用安全性xml文件.而且,您的web.xml还应具有Spring安全性过滤器.

FYR you can reference security xml file in your web.xml as below..and also your web.xml should have spring security filters.

<context-param>
 <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/your-applicationContext.xml
    /WEB-INF/your-spring-security.xml
  </param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

您还需要Spring安全性依赖项.如果您在项目中使用Maven,请添加以下依赖项,否则您可以手动下载这些jar并继续.

You need spring security dependencies as well..if you are using Maven for your project add the following dependencies else you can manually download these jars and proceed.

<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>

现在你很好. FYR通过

Now you are good to go.. FYR go through this

这篇关于在Spring中添加管理部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆