2015-08-14 168 views
3

spring petclinic sample app構建的應用程序已添加彈簧安全與自定義登錄表單。添加自定義登錄控制器與彈簧安全

該應用沒有如 this tutorial建議的WebMvcConfiguration.java類。相反,它在mvc-core-config.xml以下行:

<mvc:view-controller path="/login" view-name="login" /> 

我已經做了在日食Ctrl-H,做在整個工作區術語/login一個關鍵字搜索,但沒有控制器是可見的。我還查看了上述教程鏈接中提到的messages-jc示例項目,但在那裏也找不到「/login」控制器。

如何添加將使用標準用戶名和密碼執行彈性認證的控制器,但是這還允許我隨後在「/ login」url登錄表單時向認證過程添加其他代碼提交?

是它添加簡單下面給SomeOtherController.java

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String showLoginForm(Model model) { 
     //what goes here?  
    return "public/loginform"; 
} 

@RequestMapping(value = "/login", method = RequestMethod.POST) 
public String processLoginForm(HttpSession session, @ModelAttribute("user") User user, 
     BindingResult result, Model model, final RedirectAttributes redirectAttributes) 
{ 
     //what goes here? 
    return "secure/main"; 
} 
+0

我想你已經導入了一個Spring Security項目。主要發生在web.xml文件中的問題是您爲spring安全性正確配置了web.xml。 –

+0

@msibraham有一個鏈接到我的OP中spring petclinic的完整源代碼。應該對OP做出哪些具體的改變才能添加n因子認證? – CodeMed

+0

如果你需要進一步的幫助,讓我知道 –

回答

2

春季安全核心罐子,還有一個接口UserDetailsS​​ervice的其中有一個方法

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; 

您可以實現這個接口和你自己的邏輯創建你的代碼,就像

@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService { 

@Transactional(readOnly = true) 
public UserDetails loadUserByUsername(String username) { 
    User user = userService.findUserByUsername(username); 
    if (user != null) { 
     String password = user.getPassword(); 
     boolean enabled = user.getActive(); 
     boolean accountNonExpired = user.getActive(); 
     boolean credentialsNonExpired = user.getActive(); 
     boolean accountNonLocked = user.getActive(); 

     Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
     for (Role r : user.getRoles()) { 
      authorities.add(new SimpleGrantedAuthority(r.getAuthority())); 
     } 
     org.springframework.security.core.userdetails.User securedUser = new org.springframework.security.core.userdetails.User(
       username, password, enabled, accountNonExpired, 
       credentialsNonExpired, accountNonLocked, authorities); 
     return securedUser; 
    } else { 
     throw new UsernameNotFoundException(
       "Unable to find user with username provided!!"); 
    } 
} 

然後建立

<bean id="daoAuthenticationProvider" 
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> 
    <property name="userDetailsService" ref="userDetailsService"></property> 
</bean> 

最後,供應這個DaoAuthenticationProvider的時候需要把DaoAuthenticationProvider的目的是ProviderManager的

<bean class="org.springframework.security.authentication.ProviderManager"> 
    <constructor-arg> 
     <list> 
      <ref bean="daoAuthenticationProvider" /> 
     </list> 
    </constructor-arg> 
</bean> 

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

添加的web.xml細節

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

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:spring-config/spring-*.xml</param-value> 
</context-param> 


<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> 
+0

謝謝。你可以看看我的OP中的鏈接到petclinic示例應用程序的github代碼,並指出哪些軟件包應該包含您建議的類代碼以及petclinic中的哪些xml文件應該包含您建議的xml配置。 Petclinic是否需要實施n因素安全性的其他更改? – CodeMed

+0

如果你關心不同文件的位置,那麼你可以看看[這裏](http://www.dineshonjava.com/2013/02/spring-security-take-baby-step-to-secure。 HTML#.VdBb83U4bK5)。另外,我無法在web.xml中找到DelegatingFilterProxy –

+0

謝謝。你可以請示例delegatingFilterProxy與其他建議的代碼一起工作嗎? – CodeMed

1

涉及登錄表單您的JSP文件應像這樣。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<html> 
<head> 
<title>Spring security</title> 
<style> 
.errorblock { 
color: #ff0000; 
background-color: #ffEEEE; 
border: 3px solid #ff0000; 
padding: 8px; 
margin: 16px; 
} 
</style> 
</head> 
<body onload='document.f.j_username.focus();'> 
<h3>Login with Username and Password</h3> 

<c:if test="${not empty error}"> 
    <div class="errorblock"> 
    Your login attempt was not successful, try again. 
Caused : 
    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message} 
    </div> 
</c:if> 
<%-- <c:url value="/j_spring_security_check" var="index.htm" /> 
<form name='f' action="${index.htm}" method='POST'> --%> 
<form name='f' action="<c:url value='j_spring_security_check' />" method='POST'> 
    <table> 
    <tr> 
    <td>User:</td> 
    <td><input type='text' name='j_username' value=''> 
    </td> 
    </tr> 
    <tr> 
    <td>Password:</td> 
    <td><input type='password' name='j_password' /> 
    </td> 
    </tr> 
    <tr> 
    <td colspan='2'><input name="submit" type="submit" 
    value="submit" /> 
    </td> 
    </tr> 
    <tr> 
    <td colspan='2'><input name="reset" type="reset" /> 
    </td> 
    </tr> 
    </table> 
</form> 
</body> 
</html> 

您的spring-security.xml文件應該如下所示。

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:security="http://www.springframework.org/schema/security" 
xmlns:p="http://www.springframework.org/schema/p" 
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"> 

<security:http auto-config="true" > 
<security:intercept-url pattern="/index*" access="ROLE_USER" /> 
<security:form-login login-page="/login.htm" default-target-url="/index.htm" 
    authentication-failure-url="/loginerror.htm" /> 
<security:logout logout-success-url="/logout.htm" /> 
<!-- <security:csrf disabled="true"/> --> 
</security:http> 

<security:authentication-manager> 
<security:authentication-provider> 
<!-- <security:user-service> 
<security:user name="syed" password="1111" authorities="ROLE_USER" /> 
</security:user-service> --> 
<security:jdbc-user-service data-source-ref="dataSource"  
users-by-username-query="select username, password, active from users where username=?" 
authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur 
where us.user_id = ur.user_id and us.username =? " 
/> 
</security:authentication-provider> 
</security:authentication-manager> 
</beans> 

在配置元素中,您可以限制對具有一個或多個元素的特定URL的訪問。每個元素指定訪問URL所需的URL模式和一組訪問屬性。請記住,您必須始終在網址格式結尾處包含通配符。否則會使URL模式無法匹配具有請求參數的URL。

<security:http auto-config="true" > 
<security:intercept-url pattern="/index*" access="ROLE_USER" /> 
<security:intercept-url pattern="/Transit*" access="ROLE_USER" /> 
<security:form-login login-page="/login.htm" default-target-url="/index.htm" 
    authentication-failure-url="/loginerror.htm" /> 
<security:logout logout-success-url="/logout.htm" /> 
</security:http> 

當過我們要描述一個網址,沒有任何保障,那麼我們應該從代碼下的安全配置XML文件,上面的行刪除特定的URL。例如,如果我們不需要索引頁面的任何安全性,那麼上面的代碼應該看起來像這樣。

<security:http auto-config="true" > 
    <security:intercept-url pattern="/Transit*" access="ROLE_USER" /> 
    <security:form-login login-page="/login.htm" default-target-url="/index.htm" 
     authentication-failure-url="/loginerror.htm" /> 
    <security:logout logout-success-url="/logout.htm" /> 
    </security:http>