使用mongodb的Spring安全性不起作用?

时间:2014-11-12 20:27:32

标签: spring mongodb security

我正在使用mongodb和maven的spring security。问题是登录提供程序不会被加载,它不会抛出提供程序。 Spring安全无效我可以访问任何页面。我已经尝试了很多,但没有任何结果。

这是我的代码。

@Component
public class LoginUserDetailsService implements UserDetailsService
{

 private UserModel user;

   @Autowired
  MongoOperations op;

 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
 {

    try
    {
        Query  query= new Query(Criteria.where("username").is(username));
        this.user = op.findOne(query, UserModel.class, "users");

        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new User(this.user.getUsername(), this.user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities());

    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }

}

  public Collection<SimpleGrantedAuthority> getAuthorities()
  {
    List<SimpleGrantedAuthority> authList = getGrantedAuthorities();
    for (Role role : user.getRoles())
    {
        authList.add(new SimpleGrantedAuthority(role.getRole()));
    }
    return authList;
  }

  public List<SimpleGrantedAuthority> getGrantedAuthorities()
  {

    List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
    for (Role role : user.getRoles())
    {
        authorities.add(new SimpleGrantedAuthority(role.getRole()));
    }

    return authorities;
  }

  }

蒙戈-database.xml

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

<context:property-placeholder location="classpath:/mongo/mongo.properties" />

<context:annotation-config />

<mongo:db-factory dbname="${mongo.db.name}" />

<mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}">

    <mongo:options connections-per-host="4" connect-timeout="1000"
        max-wait-time="1500" auto-connect-retry="true" socket-keep-alive="true"
        socket-timeout="1500" write-fsync="true" />
</mongo:mongo>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory" />
</bean>

<context:component-scan base-package="se.company">
    <context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>
</beans>

弹簧security.xml文件

 <?xml version="1.0" encoding="UTF-8"?>
 <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">

<!-- For hashing and salting user passwords -->
<beans:bean id="passwordEncoder"     class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

<!-- Declare an authentication-manager to use a custom userDetailsService -->
 <beans:bean id="loginUserDetailsService" class="se.company.mongo.LoginUserDetailsService"/>
<authentication-manager>
<authentication-provider user-service-ref="loginUserDetailsService">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>

<global-method-security secured-annotations="enabled" />
<http pattern="/resources/**" security="none" />

<http auto-config="true" use-expressions="true">

    <intercept-url pattern="/index*" access="permitAll" />
    <intercept-url pattern="/login*" access="permitAll" />
    <intercept-url pattern="/logout*" access="permitAll" />

 <intercept-url pattern="/users/**" access="hasRole('ROLE_USER')" /> 
    <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/users/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" />

    <access-denied-handler error-page="/accessDenied" />
    <access-denied-handler error-page="/pageNotFound" />
    <access-denied-handler error-page="/unAuthorized" />
    <access-denied-handler error-page="/serverError" />
    <access-denied-handler error-page="/badRequest" />
    <!-- This will prevent a user from logging in multiple times - a second 
        login will cause the first to be invalidated -->
     <session-management
        session-authentication-error-url="/402">
        <concurrency-control max-sessions="1"
             error-if-maximum-exceeded="true" />
    </session-management>
     <session-management
        session-authentication-strategy-ref="sas" />

    <form-login login-page="/login" default-target-url="/admin"
        authentication-failure-url="/error" />
    <logout logout-success-url="/logout" />

</http>

</beans:beans>

MVC-调度-servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:p="http://www.springframework.org/schema/p"
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-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">


<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<!-- <bean id="loginUserDetailsService" class="se.company.mongo.LoginUserDetailsService"/> -->

<context:component-scan base-package="se.company" />

<mvc:annotation-driven />
<context:annotation-config />
<mvc:default-servlet-handler/> 

<mvc:resources mapping="/resources/**" location="/resources/" />

<context:property-placeholder location="classpath:/mongo/mongo.properties" />
<context:property-placeholder location="classpath*:*.properties" />
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
  </bean>

 </beans>

登录页面是:

  <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"  import="java.util.*"%>
   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
   <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
   <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
   <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"  %>
   <%@ page import="org.springframework.security.core.context.SecurityContextHolder" %>
   <!DOCTYPE html>
   <html>
  <head>
  <title>index</title>
  <meta charset="utf-8">

  <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/resources/css/flexlayout/flexlayout.css" />
 <head>
 </head>
 <body>
 <header>Date and Time: ${serverTime}</header>
 <div id='main'>
 <article>
 <h1 id="banner">Spring 3 security MongoDB Demo</h1>
 <form  action="<c:url value='j_spring_security_check' />" method="post">
    <table>
        <tr>
            <td>Username:</td>
            <td><input type="text" id="j_username" name="j_username" placeholder="User Name"></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" id="j_password" name="j_password" placeholder="Password">  </td>
        </tr>
        <tr>
            <td colspan="2">&nbsp;</td>
        </tr>
        <tr>
            <td colspan='2'><input value="Send" name="submit" type="submit">&nbsp;<input
                value="Reset" name="reset" type="reset"></td>
        </tr>
    </table>
 </form>

 </article>
 <nav>nav</nav>
 <aside>aside</aside>
 </div>
<footer>footer</footer>
 </body>
 </html> 

请问有人能看出问题所在吗? Will Bee感谢任何帮助。感谢

web.xml是:

<?xml version="1.0" encoding="UTF-8"?><web-app 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"
   version="2.5" metadata-complete="true">

  <display-name>Spring MVC Application</display-name>

  <!-- Spring MVC -->
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/mvc-dispatcher-servlet.xml,
        /WEB-INF/mongo-database.xml,
        /WEB-INF/spring-security.xml
    </param-value>
 </context-param>

 <error-page>
    <error-code>403</error-code>
    <location>/WEB-INF/views/403.jsp</location>
 </error-page>
 <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
 </error-page>
 <error-page>
    <error-code>402</error-code>
    <location>/WEB-INF/views/402.jsp</location>
 </error-page>
 <error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/views/500.jsp</location>
 </error-page>
<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>

</web-app>

1 个答案:

答案 0 :(得分:2)

所以Spring Security根本没有拦截任何网址?您是否在web.xml中定义了Spring Security过滤器?见http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/#ns-getting-started