Apache Shiro权限管理框架

Authentication is the process of identityverification-- you are trying to prove a user is who they say they are. To doso, a user needs to provide some sort of proof of identity that your systemunderstands and trust.

The goal of this guide is to walk youthrough how Authentication in Java is preformed in Shiro. If you haven'talready please take moment and go through Shiro's 10 MinuteTutorial so that you get abasic understanding of how to work with Shiro.

Terminology you'll need

·        Subject - Security specific user 'view' of an application user.It can be a human being, a third-party process, a server connecting to youapplication application, or even a cron job. Basically, it is anything oranyone communicating with your application.

·        Principals - A subjects identifying attributes. Firstname, last name, social security number, username

·        Credentials - secret data that are used to verifyidentities. Passwords, Biometric data, x509 certificates,

·        Realms - Security specific DAO, data access object, softwarecomponent that talkts to a backend data source. If you have usernames andpassword in LDAP, then you would have an LDAP Realm that would communicate withLDAP. The idea is that you would use a realm per back-end data source and Shirowould know how to coordinate with these realms together to do what you have todo.

How to Authenticate in Java with Shiro

In Shiro's framework, and most every otherframework for that matter, the Java authentication process can be broken upinto three distinct steps.

Steps

1.  Collect the subject's principals and credentials

2.  Submit the principals and credentials to anauthentication system.

3.  Allow access, retry authentication, or block access

Here is some code on how you do this inShiro Specifically.

Step 1 - Collect the subject's principalsand credentials

//Example usingmost common scenario:

//String username and password.  Acquire in

//system-specificmanner (HTTP request, GUI, etc)

 

UsernamePasswordTokentoken =

new UsernamePasswordToken( username, password);

 

//”Remember Me”built-in, just dothis:

token.setRememberMe(true);

 

In this particular case, we’re using aclass called UsernamePasswordToken. It is the mostcommon authentication token used in the framework.

We use this token to bundle the usernameand password we acquired in someway in our Java application. Maybe they weresubmitted via a user web form, an HTTP header, or a command line. In Shiro, itdoes not matter how you acquire them-- it is protocol agnostic.

In this example, we have decided that wewant the application to remember users when they return. So once the token iscreated, we use Shiro's built-in "Remember-me" feature by setting itto true on the token. This is done using the token's setRememberMe() method

Step 2 - Submit the principals andcredentials to an authentication system.

So we’ve collected the information in atoken and set it to remember returning users. The next step is in theAuthentication process is to submit the token to an authentication system. Yourauthentication system is represented in Shiro by security-specific DAOs, thatare referred to as Realms. For more information on realms pleasecheck out the Shiro Realm Guide.

In Shiro we try to make this part as quickand easy as humanly possible. We have it down to one line of Java code!

//With most ofShiro, you'll always want to make sure you're working with the currentlyexecuting user, referred to as the subject

SubjectcurrentUser = SecurityUtils.getSubject();

 

//Authenticate thesubject by passing

//the user name andpassword token

//into the loginmethod

currentUser.login(token);

First, we need to acquire the currentlyexecuting user, referred to as the subject. A subject is just a securityspecific view of the user----it can be a human, a process, cron job, doesn’tmatter. In Shiro, there is always a subject instance available to the currentlyexecuting thread. The concept of a subject is core to Shiro and most of theframework is centered around working with subjects. In this example, we willname this instance of subject currentUser.

To acquire the subject, we use the SecurityUtils class which isalso a core pat of Shiro's API. It will acquire the currently executing uservia the getsubject() method call. And we get back a subjectinstance that is representing who the current user is who is interacting withthe system. At this point in the example, the subject currentUser is anonymous.There is no identity associated with them.

Now with the user representation in hand,we authenticate them by just calling the login() method and submit the token we justconstructed a second ago.

Step 3 - Allow access, retryauthentication, or block access

Again really, really easy, single method call.If the login() method call is successful, then the useris logged in and associated with a user account or identity. From here, theuser can go about using your application and retain their identity throughtheir session or longer since we have set the "Remember Me" in ourexample.

But what happens if something fails in theauthentication attempt? What if they give you the wrong password or theyaccessed the system too many times, maybe their account is locked? In thiscase, Shiro will throw an exception. This is where Shiro's rich exceptionhierarchy comes into play.

try {

    currentUser.login(token);

} catch ( UnknownAccountException uae ) { ...

} catch ( IncorrectCredentialsException ice ) { ...

} catch ( LockedAccountException lae ) { ...

} catch ( ExcessiveAttemptsException eae ) { ...

} ... catch your own ...

} catch ( AuthenticationException ae ) {

//unexpected error?

}

//No problems, showauthenticated view…

You can take that method call and wrap itin a try/catch block and you can catch all sort of exceptions if you want tohandle them and react accordingly. In addition to a rich set of exceptions thatShiro offers, you can create your own if you need custom functionality. Formore information, follow this link documentation on AuthenticationException.

Security Tip
Security best practice is to give generic login failure messages to users because you do not want to aid an attacker trying to break into your system.

"Remember Me" Support

As shown in the example above, Shirosupports the notion of "remember me" in adition to the normal loginprocess.  

In Shiro, the Subject object supports twomethods : isRemembered() and isAuthenticated().

A "remembered" subject has anidentity (it is not anonymous) and their identifying attributes,referred to asprincipals, are remembered from a successful authentication during a previoussession.

An authenticated subject has proved theiridentity during theircurrent session.

Warning
If a subject is remembered, it DOES NOT mean they are authenticated.

Remembered vs Authenticated

In shiro it is very important to note thata remembered subject is not an authenticated subject. A check against isAuthenticated() is a much more strict check becauseauthentication is the process of proving you are who you say you are. When auser is only remembered, the remembered identity gives the system an idea whothat user probably is, but in reality, has no way of absolutely guaranteeing ifthe remembered Subject represents the user currently using the application.Once the subject is authenticated, they are no longer considered onlyremembered because their identity would have been verified during the currentsession.

So although many parts of the applicationcan still perform user-specific logic based on the remembered principals, suchas customized views, it should never perform highly-sensitive operations untilthe user has legitimately verified their identity by executing a successfulauthentication attempt.

For example, a check to see if a subjectcan access financial information should almost always depend on isAuthenticated(), notisRemembered(), to guarantee a verified identity.

He is a scenario to help illustrate whythe the distinction between isAuthenticated and isRemembered is important.

Let's say you're using Amazon.com. You login and you add some books to your shopping cart. A day goes by. Of course youruser session has expired and you've been logged out. But Amazon"remembers" you, greets you by name, and is still giving youpersonalized book recommendations. To Amazon, isRemembered() would return TRUE. What happens if you try to use one of the credit cardson file or change your account information? While Amazon "remembers"you, isRemembered() = TRUE, it is not certain that you are in factyou,isAuthenticated()=FALSE. So before youcan perform a sensitive action Amazon needs to verify your identity by forcingan authentication process which it does through a login screen. After thelogin, your identity has been verified and isAuthenticated()=TRUE.

This scenario happens very often over theweb so the functionality is built into Shiro helping you easily make thedistinction yourself.

Logging Out

Finally, when the user is done using theapplication, they can log out. And in Shiro, we make logging out quick and easywith a single method call.

currentUser.logout();//removes allidentifying information and invalidates their session too.

When you log out in Shiro it will closeout the user session and removes any associated identity from the subjectinstance. If you're using RememberMe in a web environment, then .logout() will, by default, also delete theRememberMe cookie from the browser.

Lend a hand with documentation

While we hope this documentation helps youwith the work you're doing with Apache Shiro, the community is improving andexpanding the documentation all the time. If you'd like to help the Shiroproject, please consider corrected, expanding, or adding documentation whereyou see a need. Every little bit of help you provide expands the community andin turn improves Shiro.

The easiest way to contribute yourdocumentation is to send it to the User Forum or the User Mailing List.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值