1. 程式人生 > >使用Apache Shiro進行身份認證

使用Apache Shiro進行身份認證

本文介紹瞭如何在WEB應用中使用Shiro進行身份認證。

在web.xml檔案中配置一個Servlet ContextListener的監聽器和Filter過濾器。

<listener>
		<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
	</listener>
	<filter>
		<filter-name>ShiroFilter</filter-name>
		<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>ShiroFilter</filter-name>
		<url-pattern>/login.do</url-pattern>
	</filter-mapping>

JSP頁面提交使用者名稱和口令。
<FORM name="form1" action="login.do" method="POST">
	<TABLE cellSpacing=0 cellPadding=0 align=center
		border=0>
		<TBODY>
			<TR>
				<TD width=250>
					<TABLE cellSpacing=3 cellPadding=0 border=0>
						<TBODY>
							<TR>
								<TD width=90><IMG height=29
									src="images/title_yhm.gif" width=90></TD>
								<TD><INPUT class=logininput name=loginName>
								</TD>
							</TR>
							<TR>
								<TD width=90><IMG height=27
									src="images/title_mima.gif" width=90></TD>
								<TD><INPUT class=logininput type=password
									name=password></TD>
							</TR>
							<TR>
								<TD width=90></TD>
								<TD align="right"></TD>
							</TR>
						</TBODY>
					</TABLE>
				</TD>
				<TD vAlign=top>
					<TABLE cellSpacing=6 cellPadding=0 border=0>
						<TBODY>
							<TR>
								<TD><IMG style="CURSOR: hand"
									onclick=doSubmit() height=35
									src="images/button_login.gif" width=77
									border=0></TD>
							</TR>
						</TBODY>
					</TABLE>
				</TD>
			</TR>
		</TBODY>
	</TABLE>
</FORM>

Shiro的配置檔案,/WEB-INF/Shiro.ini。
main]
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource  
ds.serverName = 127.0.0.1
ds.user = root
ds.password = 123456
ds.databaseName = shiro  
ds.url = jdbc:mysql://127.0.0.1:3306/shiro  
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm  
jdbcRealm.permissionsLookupEnabled = true  
jdbcRealm.authenticationQuery = SELECT password FROM user_credence_information WHERE username = ?  
jdbcRealm.dataSource = $ds

shiro.loginUrl = /login.jsp

[users]
# format: username = password, role1, role2, ..., roleN


[roles]
# format: roleName = permission1, permission2, ..., permissionN

[urls]
# The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but
# the 'authc' filter must still be specified for it so it can process that url's
# login submissions. It is 'smart' enough to allow those requests through as specified by the
# shiro.loginUrl above.
/success.jsp = authc

服務端認證程式。
public class LoginController implements Controller {
	private static final Log log = LogFactory.getLog(LoginController.class);
	protected ErrMg error;

	public ModelAndView doReturnError(HttpServletRequest request,
			HttpServletResponse response, ErrMg message, String errpath) {
		request.setAttribute("Error_Message", message);
		return new ModelAndView(errpath);

	}
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String loginName = request.getParameter("loginName");
		String loginPwd = request.getParameter("password");
		log.info("使用者認證開始:" + loginName + " , " + loginPwd);
		String userid = null;
		String username = null;
		error = new ErrMg();
		AuthenticationToken token = new UsernamePasswordToken(loginName,
				loginPwd);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
			userid = (String)currentUser.getPrincipal();
			log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
			log.info("使用者認證完畢:" + loginName + " , " + userid);
			HttpSession session = request.getSession(true);
			session.setAttribute("USERINFORMATION", userid);
			session.setAttribute("USERNAME", userid);
			return new ModelAndView("success.jsp");
		} catch (UnknownAccountException uae) {
			log.info("使用者認證失敗:" + "username wasn't in the system.");
			error.setErrorMessage("username wasn't in the system.");
		} catch (IncorrectCredentialsException ice) {
			log.info("使用者認證失敗:" + "password didn't match.");
			error.setErrorMessage("password didn't match.");
		} catch (LockedAccountException lae) {
			log.info("使用者認證失敗:" + "account for that username is locked - can't login.");
			error.setErrorMessage("account for that username is locked - can't login.");
		} catch (AuthenticationException ae) {
			log.info("使用者認證失敗:" + "unexpected condition.");
			error.setErrorMessage("unexpected condition.");
		}
		
		return this.doReturnError(request, response, error, "error.jsp");
	}

}



相關推薦

使用Apache Shiro進行身份認證-密碼加密

在進行身份認證時,使用者的密碼一般是用密文的形式存放在資料庫中。這樣在做比對時不能直接使用使用者提交的明文口令。 在Shiro中使用org.apache.shiro.authc.credential.SimpleCredentialsMatcher做憑證資訊的比對。Simp

使用Apache Shiro進行身份認證

本文介紹瞭如何在WEB應用中使用Shiro進行身份認證。 在web.xml檔案中配置一個Servlet ContextListener的監聽器和Filter過濾器。 <listener> <listener-class>org.apache.s

Shiro(2)-身份認證

基本概念 身份驗證 即在應用中誰能證明他就是他本人。一般提供如他們的身份ID 一些標識資訊來表明他就是他本人,如提供身份證,使用者名稱/密碼來證明。在 shiro 中,使用者需要提供principals (身份)和credentials(證明)給shiro,從而應用能驗證使用者身份

.NetCore採取JWT方式進行身份認證

  驗證與授權 Authentication(身份認證) 認證是系統對請求的使用者進行身份識別的過程。 Authorization (授權) 授權是對認證通過後的使用者進行許可權分配的過程。授權簡單理解就是:識別認證後用戶所擁有哪些許可權,從而開放伺服器相對應的資源; 我們通俗點來解釋身

Spring Boot 整合 Shiro 進行登入認證

安全無處不在,趁著放假讀了一下 Shiro 文件,並記錄一下 Shiro 整合 Spring Boot 在資料庫中根據角色控制訪問許可權 簡介 Apache Shiro是一個功能強大、靈活的,開源的安全框架。它可以乾淨利落地處理身份驗證、授權、企業會話管理和

Apache Shiro 移動端認證回撥函式授權登入

在J2EE專案開發中,若用到Apache Shiro許可權框架,若需為移動端提供登入介面並提供授權認證則需要對移動端提供的登入資訊進行處理,封裝到token中,然後交由Apache Shiro進行認證回撥函式授權登入,下面是本人在專案開發中的實現方式: /**

Apache James SMTP身份認證

SMTP身份認證 (SMTP AUTH) SMTP身份認證是一種保證SMTP伺服器安全的方法,它要求希望通過SMTP伺服器轉發 郵件(即郵件最終傳送給另一個SMTP伺服器)的使用者在傳送訊息之前必須先向James表明自己的身份。 這樣垃圾郵件傳送者就不能用你

SpringBoot學習:整合shiro身份認證和許可權認證),使用EhCache快取

專案下載地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)在pom.xml中新增依賴: <properties> <shiro.version>1.3.2</shiro.ve

iOS 8使用Touch ID進行身份認證

   iOS 8的SDK開放了Touch ID的介面.從WWDC的視訊中可以看到Touch ID應用在兩個方面:用於Key Chain加密和用於授權.iOS 8正式版釋出以後我們可以看到Evernote的iOS app已經集成了該功能.下面來看看如何實現使用Touch ID

Shiro身份認證(Authentication)

Apache Shiro 是一個強大且靈活的 Java 開源安全框架,擁有登入認證、授權管理、企業級會話管理和加密等功能,相比 Spring Security 來說要更加的簡單。本文主要介紹 Shiro 的登入認證(Authentication)功能,主要從 Shiro 設計

Apache Shiro:Java 認證授權框架 SSO 單點等了解決方案

package shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.config.IniSecurityManagerFactory; import or

Shiro登入身份認證(從SecurityUtils.getSubject().login(token))到Realm的doGetAuthenticationInfo

ssm框架下,controller接收到登入請求交給Service並開始處理流程:1.Service的login方法:@Service public class SysUserServiceImpl implements SysUserService { @Autow

如何在PHP中進行身份認證

<? if(!isset($PHP_AUTH_USER)) { Header("WWW-Authenticate: Basic realm=請輸入你的使用者名稱和密碼:"); Header("HTTP/1.0 401 Unauthorized"); echo "驗證失敗,你不能網路資源!"; exit;

APP利用token機制進行身份認證(理解token機制+簡單Java程式碼實現)

什麼是token token的意思是令牌,想象一下用過的qq令牌,是來自(騰訊)服務端生成的一串字元,作為客戶端(我們自己)進行請求的一個標識。比如說:改qq密碼。而這裡我們是自己開發App,我們的使用者用token請求登入,我們對他進行身份認證。 當用戶第一

asp.net core 使用identityServer4的密碼模式來進行身份認證(一)

.sh 錯誤 memory msi entity factory password fig 重載 原文:asp.net core 使用identityServer4的密碼模式來進行身份認證(一)IdentityServer4是ASP.NET Core的一個包含OpenID和

在 ASP.NET Core 應用中使用 Cookie 進行身份認證

## Overview 身份認證是網站最基本的功能,最近因為業務部門的一個需求,需要對一個已經存在很久的小工具網站進行改造,因為在逐步的將一些離散的系統遷移至 .NET Core,所以趁這個機會將這個老的 .NET Framework 4.0 的專案進行升級 老的專案是一個 MVC 的專案並且有外網訪問的

ShiroApache Shiro架構之身份認證(Authentication)

trac pretty asm 安全保障 軟件測試 釋放 model tac 讀取配置文件 Shiro系列文章: 【Shiro】Apache Shiro架構之權限認證(Authorization) 【Shiro】Apache Shiro架構之集成web

Apache shiro叢集實現 (三)shiro身份認證Shiro Authentication)

<span style="font-size:18px;">package com.api6.shiro.demo1; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; impo

Apache Shiro 身份認證例子

1. 概述 在本例子中使用Apache Shiro在Web應用中實現身份認證,將Shiro與Spring進行整合,使用內嵌的derby資料庫儲存使用者資訊。 持久層為Hibernate,資料庫連線池為alibaba druid。 2. 準備 建立一個內嵌的derby資料庫,

shiro 配置註解後無權訪問不進行頁面跳轉異常:org.apache.shiro.authz.UnauthorizedException: Subject does not have permission

class bject ram body pac framework simple -- 管理 該問題需要使用異常管理: <!-- 無權訪問跳轉的頁面 --> <bean class="org.springframework.web.ser