iT邦幫忙

DAY 19
0

無痛學習SpringMVC與Spring Security系列 第 19

[Security]Spring Security簡介與第一個login畫面

  • 分享至 

  • xImage
  •  

學習Spring Security我買了Packt出版的Spring Security 3.1來看以及參考Spring Security的官方文件,當然也包括網路資源,IT鐵人賽開始的時候我還沒學完,大致瀏覽過,感想是Spring Security有點難學的,當然要做出基本的login/logout是不困難,但困難的點在於權限的設定以及挑選用什麼機制來做驗證,Spring Security幾乎支援所有的Authentication(認證)機制,如JDBC-based, LDAP, Client Certificate, OpenID, Central Authentication Service(CAS), Acess Control List (ACL),當然還有另外的專案Spring OAuth支援OAuth認證機制,慧根有限的我僅能分享JDBC-Based, ACL認證機制,以及Spring Security Core Service的部分,如未認證的使用者將看不到網頁的某些元素以及,Remember me等。

ㄉㄚ

今天介紹以Java Config的方式設定Spring Security,之前介紹SiteMesh的時候已經將SecurityConfig寫好了,今天將延續,設定存取網站中任何網頁時,需要驗證才能檢視網頁,首先需要設定初始化Spring Security,即新增一個filter org.springframework.web.filter.DelegatingFilterProxy,來攔截所有request,class code及對應xml註解的如下

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class WebSecurityConfig extends
		AbstractSecurityWebApplicationInitializer {
		/**
		 * extends AbstractSecurityWebApplicationInitializer等同
		 * <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>
    		
    		當任何request時o.s.web.filter.DelegatingFilterProxy呼叫SpringSecurityFilterChain
		 */

}

接著新增SecurityConfig負責後續的攔截URL以及權限設定,其code以及xml註解如下:

@EnableWebSecurity //Enable springFliterChain
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		http.
			authorizeRequests()
			.anyRequest() //對象為所有網址
			.authenticated() //存取必須通過驗證
			.and()
			.formLogin() //若未不符合authorize條件,則產生預設login表單
			.and()
			.httpBasic(); //產生基本表單
	}
	/**
	 * 以上程式碼等同於xml
	 * <http user-expression="true">
	 * <intercept-url pattern=/** access="authenticated"
	 * <form-login />
	 * <http-basic />
	 **/

	@Override
	protected void configure(AuthenticationManagerBuilder auth)
			throws Exception {
		// TODO Auto-generated method stub
		auth //Builder Design Pattern
			.inMemoryAuthentication() //自訂Runtime時的使用者帳號
				.withUser("admin") //新增user
				.password("admin12345") //指定密碼
				.roles("ADMIN", "USER") //指派權限群組
				.and() //再新增使用者
				.withUser("user")
				.password("user12345")
				.roles("USER");
	}
	/**
	 *<authentication-manager>
    	<authentication-provider>
    		<user-service>
    			<user name="admin" password="admin12345"  authorities="ROLE_ADMIN, ROLE_USER"/>
    			<user name="user" password="user12345"  authorities="ROLE_USER"/>
    		</user-service>
    	</authentication-provider>
     </authentication-manager>
	 */
}

formLogin目前未指定Login form的url位址,Spring Security會自動產生一個最簡易的,另外SecurityConfig要加入getRootConfigClasses,如下

@Override
	protected Class<?>[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return new Class<?> []{PersistenceConfig.class, SecurityConfig.class}; 
	}

啟動Server,console log有記錄到spingSecurityFilter有成功啟動

23:59:15 [localhost-startStop-1] ContextLoader - Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
23:59:15 [localhost-startStop-1] ContextLoader - Root WebApplicationContext: initialization completed in 4273 ms
23:59:15 [localhost-startStop-1] DelegatingFilterProxy - Initializing filter 'springSecurityFilterChain'
23:59:15 [localhost-startStop-1] DelegatingFilterProxy - Filter 'springSecurityFilterChain' configured successfully

產生的預設login 畫面如下

00:07:43 [http-nio-8080-exec-2] DelegatingAuthenticationEntryPoint - Match found! Executing org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint@3a7a3c22
00:07:43 [http-nio-8080-exec-2] DefaultRedirectStrategy - Redirecting to 'http://localhost:8080/SpringMVC/login'

Console log紀錄AccessDeniedException:

00:07:43 [http-nio-8080-exec-2] ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied

打入Admin及其密碼,登入成功畫面及Console log如下

Console log紀錄UsernamePasswordAuthenticationFilter - Authentication success,重新導向至預設網站根目錄。

00:09:55 [http-nio-8080-exec-4] UsernamePasswordAuthenticationFilter - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: C66D8794777A252AB6FC2D3182AB2A54; Granted Authorities: ROLE_ADMIN, ROLE_USER
00:09:55 [http-nio-8080-exec-4] SavedRequestAwareAuthenticationSuccessHandler - Redirecting to DefaultSavedRequest Url: http://localhost:8080/SpringMVC/
00:09:55 [http-nio-8080-exec-4] DefaultRedirectStrategy - Redirecting to 'http://localhost:8080/SpringMVC/'

上一篇
[View]輸出PDF檔案
下一篇
[Security]Spring設定需認證的URL以及自訂login表單
系列文
無痛學習SpringMVC與Spring Security31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
神威
iT邦研究生 4 級 ‧ 2018-10-08 09:21:01

joombuopre
你好:
想請教您有關spring-security的問題可以嗎?

我現在試用spring-security 3 當中

我的環境 netbeans8.1+ Tomcat 8.0.26 + java web application + spring-security 3.2
我發現只要加入

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

就會一直錯誤

deploy?config=file%3A%2FC%3A%2FUsers%2Fadmin%2FAppData%2FLocal%2FTemp%2Fcontext286657186841485390.xml&path=/t1
FAIL - Deployed application at context path /t1 but context failed to start
C:\Users\admin\Documents\NetBeansProjects\t1\nbproject\build-impl.xml:1130: The module has not been deployed.
See the server log for details.

而 server log錯誤的地方是

 <target if="netbeans.home" name="-run-deploy-nb">
        <nbdeploy clientUrlPart="${client.urlPart}" debugmode="false" forceRedeploy="${forceRedeploy}"/>
    </target>

想問該如何解決這問題
我已經爬了很多文章照做,他還是一直錯誤.....
能不能幫我一下,謝謝

我要留言

立即登入留言