How to get user information from ldap? - java

I am using apache shiro for ldap authentification:
Factory<SecurityManager> ldapFactory = new IniSecurityManagerFactory("classpath:active.ini");
SecurityManager sManager = ldapFactory.getInstance();
SecurityUtils.setSecurityManager(sManager);
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
try {
currentUser.login(token);
} catch (UnknownAccountException ex) {
logger.info("Unknown user");
} catch (IncorrectCredentialsException ex) {
logger.info("Incorrect credentials");
} catch (LockedAccountException ex) {
logger.info("Account is Locked");
} catch (AuthenticationException ex) {
logger.info("Authentication Exception");
}
}
logger.info("User [" + currentUser.getPrincipal() +"] logged succesfully");
currentUser.logout();
Calling currentUser.getPrincipal(), I've got only email address from the logged user.
How to get more user information, for example lastname, firstname, etc?

getPrincipal() only returns the subject's identifier. Try to use getPrincipals() instead.
Object getPrincipal()
Returns this Subject's application-wide uniquely identifying
principal, or null if this Subject is anonymous.
PrincipalCollection getPrincipals()
Returns this Subject's principals
(identifying attributes) in the form of a PrincipalCollection or null
if this Subject is anonymous
Apache Shiro API (JavaDoc)

You could extend the LDAP Realm. and add more context to Principal/PrincipalCollection (or return a custom object or your Principal)
This is an old thread, but I find myself digging it up every once and a while and covers this topic (It mentions JSecurity which is the original project name for Shiro).

Related

Create custom messages for expired and locked user

I want to return custom message if user during authentication process is locked or expired. I tried to implement this:
#Service
public class UserDetailsHandler implements UserDetailsService {
#Autowired
private UsersService usersService;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final Optional<Users> user = usersService.findByLogin(username);
if (!user.isPresent()) {
throw new UsernameNotFoundException("User '" + username + "' not found");
}
return user
.map(value -> {
return new User(
value.getLogin(),
value.getEncryptedPassword(),
value.getEnabled(),
hasAccountExpired(value.getExpiredAt()),
hasPasswordExpired(value.getPasswordChangedAt()),
hasAccountLocked(value.getLockedAt()),
Collections.singleton(new SimpleGrantedAuthority(value.getRole().getAuthority()))
);
}).orElseThrow(() -> new UsernameNotFoundException("User with username " + username + " not found"));
}
private boolean hasAccountExpired(LocalDateTime account_expired_at) {
return account_expired_at == null;
}
Full code: GitHub
The question is how to create handlers which return some custom message if the validation returns true value for statuses user locked or user expired?
The best option for you is:
Implement Spring UserDetails in your entity Users.
Check in loadUserByUsername if the user has been locked, etc using Spring AccountStatusUserDetailsChecker class.
Add into your EngineExceptionHandler the required methods to manage those exceptions: LockedException, AccountExpiredException, etc
You will see examples of above points in the following links:
Point 1
Point 2
Points 2-3
Well I briefly look at your codes and you implement a JwtTokenFilter that will some how calls the UserDetailsHandler .
In JwtTokenFilter , you already catch and handle EngineException which contain the HTTP status codes and a message. An HTTP response will be sent out which the status and the body message that are the same as what defined in the caught EngineException
It seems that you already configure everything for it to work , so just simply throw EngineException with the suitable HTTP status code and message from the UserDetailsHandler . Something like :
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users user = usersService.findByLogin(username)
.map(value -> {
return new User(
value.getLogin(),
value.getEncryptedPassword(),
value.getEnabled(),
hasAccountExpired(value.getExpiredAt()),
hasPasswordExpired(value.getPasswordChangedAt()),
hasAccountLocked(value.getLockedAt()),
Collections.singleton(new SimpleGrantedAuthority(value.getRole().getAuthority()))
).orElseThrow(()-> throw new UsernameNotFoundException("User '" + username + "' not found"));
if (user.isAccountLock()){
throw new EngineException(HttpStatus.UNAUTHORIZED , "Custom message for account lock ......")
}
if(user.isAccountExpired()){
throw new EngineException(HttpStatus.UNAUTHORIZED , "Custom message for account expired... ......")
}
}
Spring Security uses the messages.properties which consist of default messages, we can add our custom message with the same. Add messages.properties and add a message as shown below.
AccountStatusUserDetailsChecker.expired=User account has expired
AccountStatusUserDetailsChecker.locked=User account is locked
AbstractUserDetailsAuthenticationProvider.expired=User account has expired
AbstractUserDetailsAuthenticationProvider.locked=User account is locked
You may find the default messages here
Its simple 2 steps approach. User expired means token expired
Step 1
Modify JWTTokenProvider Class to add a custom header to Http Servlet Request using setAttribute() method.
JwtTokenProvider.java
public boolean validateToken(String token,HttpServletRequest httpServletRequest){
try {
Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
return true;
}catch (SignatureException ex){
System.out.println("Invalid JWT Signature");
}catch (MalformedJwtException ex){
System.out.println("Invalid JWT token");
}catch (ExpiredJwtException ex){
System.out.println("Expired JWT token");
httpServletRequest.setAttribute("expired",ex.getMessage());
}catch (UnsupportedJwtException ex){
System.out.println("Unsupported JWT exception");
}catch (IllegalArgumentException ex){
System.out.println("Jwt claims string is empty");
}
return false;
}
Step 2
Modify commence method in JwtAuthenticationEntryPoint.class to check expired header in http servlet request header that we added in step 1.
JwtAuthenticationEntryPoint.java
#Override
public void commence(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
final String expired = (String) httpServletRequest.getAttribute("expired");
System.out.println(expired);
if (expired!=null){
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,expired);
}else{
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Invalid Login details");
}
}
It is a best practice to return detailed error messages in any REST API. We used this to customize spring rest jwt token expired response to return more detailed error response. We can use this method not only for token expired but also for other jwt token exceptions like SignatureException, Malformed JwtException, UnsupportedJwtException and IllegalArgumentException.

Apache Shiro: not able to access secured URL although logged in successfully

Im currenlty working on a Java EE Web application with Spring MVC.
I want to secure it with Apache Shiro and the form-based authentication with the
FormAuthenticationFilter is already working.
Now i want to customize the login and write my own login-controller.
Here is my Problem: the authentication works, I don't get any exceptions, but I am still unable to acess the secured URL (/welcome.jsp), even if I try to access it directly, although I am logged in correctly (Subject.isAuthenticated returns true) .
Here is my shiro.ini:
# =======================
# Shiro INI configuration
# =======================
[main]
authc = org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter
#authc = org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authc.loginUrl = /login.jsp
authc.successUrl = /welcome.jsp
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
securityManager.sessionManager = $sessionManager
[users]
admin=admin, ROLE_ADMIN
[roles]
ROLE_ADMIN = *
[urls]
/login.jsp = authc
/welcome.jsp = authc
And here is the method in the respective controller class:
#RequestMapping(value="/login", params ={"username","password"})
public ModelAndView login(HttpServletRequest request, HttpServletResponse response,
#RequestParam("username") String username, #RequestParam("password") String password) {
if (!this.currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
this.currentUser.login(token);
} catch (UnknownAccountException uae) {
logger.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
logger.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
logger.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
catch (AuthenticationException ae) {
//TODO
}
logger.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
}
String message = "";
ModelAndView modelAndView = new ModelAndView("login", "message", message);
String fallbackUrl = "/welcome.jsp";
try
{
WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
}
catch (IOException e)
{
e.printStackTrace();
}
return modelAndView;
}
I would be very happy, if someone could tell me, what I'm doing wrong, I am stuck at this for a few days now and haven't found anything on the web.
With best regards,
M.B.
P.S. I haven't posted my web.xml, and my pom.xml because shiro is already working with the FormAuthenticationFilter. But if someone still needs these files to give me an answer, it is no problem, to post them too.
UPDATE 1: It has to be an issue with Shiro itself. If I escape only the last line in the shiro.ini file,
#/welcome.jsp = authc
the redirection works correctly and the username: "admin" is only shown on the welcome-page, if I enter the username and password correctly.
For some reason, shiro doesn't accept the authenticated user but I have absolutely no idea why.
I finally found a solution, I hope, this will help somebody else.
The problem was that I created a field for the currentUser (as you can see in my method) and I initialized it in the constructor of the Controller. At that time, no security manager was found, so I created a SecurityManager instance too, but now this was a different one, than apache shiro used for redirecting me.
To solve this, i simply had to instanciate
this.currentUser = SecurityUtils.getSubject();
in the respective method and not in the constructor.

Shiro not redirecting to loginUrl after failed attempts to log in

Using Spring Boot I am configuring the following filter
#Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter() {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
Map<String, String> filterChainDefinitionMapping = new HashMap<>();
/*
* URL path expressions are evaluated against an incoming request in the order they are defined and the FIRST MATCH WINS. For example, let's asume that there are the following chain definitions:
/account/** = ssl, authc
/account/signup = anon
If an incoming request is intended to reach /account/signup/index.html (accessible by all 'anon'ymous users), it will never be handled!. The reason is that the /account/** pattern matched the incoming request first and 'short-circuited' all remaining definitions.
Always remember to define your filter chains based on a FIRST MATCH WINS policy!
* */
filterChainDefinitionMapping.put("/login.html", "authc");
filterChainDefinitionMapping.put("/logout", "logout");
filterChainDefinitionMapping.put("/css/**", "anon");
filterChainDefinitionMapping.put("/register/**", "anon");
filterChainDefinitionMapping.put("/**", "authc");
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMapping);
shiroFilter.setSecurityManager(securityManager());
shiroFilter.setLoginUrl("/login.html");
shiroFilter.setSuccessUrl("/");
shiroFilter.setUnauthorizedUrl("/unauthorized.html");
Map<String, Filter> filters = new HashMap<>();
filters.put("anon", new AnonymousFilter());
filters.put("authc", new FormAuthenticationFilter());
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setRedirectUrl("/login.html?logout");
filters.put("logout", logoutFilter);
filters.put("roles", new RolesAuthorizationFilter());
filters.put("user", new UserFilter());
shiroFilter.setFilters(filters);
return shiroFilter;
}
However, whenever I try to login with wrong credentials the redirection never happens. I do get the "shiroLoginFailure" attribute holding the UnknownUserException.
(Logging in with the correct credentials works fine)
Any ideas?
Mariosk89, how do you resolve the /login.html?
It might be need to resolve redirect like this:
#RequestMapping("/login")
public String login(String username, String password) {
Subject currentUser = SecurityUtils.getSubject();
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
try {
currentUser.login(new UsernamePasswordToken(username, password));
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
return "login";
}
return "redirect:index";
} else {
return "login";
}
}
Reference: https://github.com/lenicliu/examples/tree/master/examples-spring-boot/examples-spring-boot-shiro
For more exception solution, refer http://shiro.apache.org/10-minute-tutorial.html
try {
currentUser.login( token );
//if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
//username wasn't in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
//password didn't match, try again?
} catch ( LockedAccountException lae ) {
//account for that username is locked - can't login. Show them a message?
}
... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
//unexpected condition - error?
}

How do I add both Facebook Login and Email registration to my Google Cloud Endpoints App (Java)?

So I have an app which uses Google App Engine and Google Cloud Endpoints as it's backend in Java. I'm currently working on User authentication and here is what I'm trying to do:
When user first opens the app, they'll have option to either "Login through Facebook" or signup using their email address. Then this data would be stored in a user object and after registration would direct them to the app homepage. It will be saved in their preferences so that they don't need to login every time they open the app (if ever).
Now I heard you can use a custom authenticator for Facebook, but there's not much documentation regarding this. How can I get the email registration and Facebook Login options to be implemented with Google Cloud Endpoint's Authenticator? Or should I make a different approach?
Thanks.
My approach is using the Facebook login method (Facebook SDK for Android). The Facebook authentication process returns (on success) an object from which I can get the user's email then I save it in my Endpoints class using Datastore API. To check if user already logged in I chose the SharedPreferences approach with GSON library to parse objects into JSON String and save them in the prefs.
Links and my sample codes below :
Regarding the Authenticator I found this SO answer
More info about Facebook login method
Saving custom objects in SharedPreferences
Getting user's email through Facebook auth
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
if (isSessionCalled == false) {
Log.i(TAG, "Logged in...");
System.out.println("Token=" + session.getAccessToken());
new Request(
session,
"/me",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
if (response != null) {
GraphObject object = response.getGraphObject();
String email = (String) object.getProperty("email");
Log.i(TAG, "user email : " + email);
String firstName = (String) object.getProperty("first_name");
String lastName = (String) object.getProperty("last_name");
mUserTask = new UserAsyncTask();
mUserTask.execute(email);
}
}
}
).executeAsync();
isSessionCalled = true;
}
else {
Log.w(TAG, "session called twice");
}
}
else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
Storing the user in my backend :
#ApiMethod(name = "storeUserModel")
public UserModel storeUserModel(UserModel userModel) throws UserAlreadyExistsException, UserNotFoundException {
logger.info("inside storeUser");
String email = userModel.getEmail();
UserModel checkUser = getUserModel(email);
logger.info("after getUserModel with email " + email);
if (checkUser == null) {
logger.info("inside checkUser is NULL");
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction txn = datastoreService.beginTransaction();
try {
Entity userEntity = new Entity(UserModel.class.getSimpleName(), email);
userEntity.setProperty("nickname", userModel.getNickname());
// TODO save the pheromones with the key of userEntity
datastoreService.put(userEntity);
txn.commit();
storePheromoneList(userModel.getPheromoneList(), userEntity.getKey(), datastoreService);
} finally {
if (txn.isActive()) {
logger.severe("rolled back with email : " + email);
txn.rollback();
}
}
}
else {
throw new UserAlreadyExistsException();
}
return userModel;
}
A class that triggers calls to my backend
public class EndpointsServer implements Server {
private static final String TAG = "EndpointsServer";
final UserModelApi userEndpointsApi;
public EndpointsServer() {
UserModelApi.Builder builder = new UserModelApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
userEndpointsApi = builder.build();
}
#Override
public User getUser(String email) {
User user = null;
try {
Log.d(TAG, "in getUser with email " +email);
// get user from db
UserModel userModel = userEndpointsApi.getUserModel(email).execute();
if (userModel != null) {
Log.d(TAG, "user != null with email " + email);
user = new User(userModel);
}
} catch (IOException e) {
e.printStackTrace();
}
return user;
}
}
Storing user on successful login :
String userString = gson.toJson(user, User.class);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(USER_KEY, userString);
editor.commit();
There's more to it like another client side class to build the api call to the backend and lots of other details. I can post it if you want.
I can't speak on Java but I started with Python by looking at this repo on Github:
https://github.com/loudnate/appengine-endpoints-auth-example
This shows you an example on how to write a custom authenticator with Facebook Login. Writing your own authentication I think you should be able to find some examples. The only thing you need to do after is to use the same User entity.
And I suggest you do some reading on how OAUTH 2.0 works so you don't get too confused on the task you need to do.
Basically:
On your client side, whether web or android, get a facebook access token, sends it to your endpoint service. Exchange for a access token of your own. At the same time, create your User object in datastore and associate the access token.
Then all your subsequent request should use this access token to get access to your endpoint backend. (Do a user check on your endpoint API method.)

Use custom exceptions in Spring Security

I have created a custom AuthenticationProvider to perform custom security checks. I have also created custom exceptions that inherit from AccountStatusException to notify user status problems such as when the user has not verified his account for an specific period of time.My UserDetails is also acustom implementation.
Here is the code for the security checks I perform. Code that is irrelevant to the case has been omitted.
public class SsoAuthenticationProvider implements AuthenticationProvider {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = (String) authentication.getPrincipal();
User user = null;
if (username != null) {
user = getUserRepository().findByUserName(username);
if (user != null) {
if (user.getEnabled() != 0) {
if ((user.getUserDetail().getConfirmed() != 0)
|| ((new Date().getTime() - user.getUserDetail().getRequestDate().getTime()) / (1000 * 60 * 60 * 24)) <= getUnconfirmedDays()) {
if (getPasswordEncoder().isPasswordValid(user.getPassword(),
(String) authentication.getCredentials(), user)) {
user.authenticated = true;
user.getAuthorities();
}
} else {
throw new UserNotConfirmedAndTimeExceeded(
"User has not been cofirmed in the established time period");
}
} else {
throw new DisabledException("User is disabled");
}
} else {
throw new BadCredentialsException("User or password incorrect");
}
} else {
throw new AuthenticationCredentialsNotFoundException("No credentials found in context");
}
return user;
}
}
The SsoAuthenticationProvider checks:
That the username is registered (exists in the db)
That the user has confirmed his email
If the user has not confirmed his email, check that he is still in the grace period (this is a few days we give users to confirm their email while letting them access the site)
If the user has not confirmed email and he is not in the grace period, throw security exception to signal these status and reject authentication
The problem is that not all of these exceptions are thrown up the stack up to the controller so it seems impossible to inform the user about the login problem.
Using UserDetails methods such as isEnabled() (and similar) is not a possibility as the semantics of our different user account statuses are completely different.
Is this the right approach to build custom security with custom exceptions? Should i implement sth else to make this work?
To close the previously asked question let me explain what we did.
As I commented to previous responses, using provided methods in UserDetails objectis not feasible as you cannot capture all the login failure semantics with the given methods. In our case these semantics are still very limited but in other cases it could indfinitely extend over time to express different user situations.
The exception approach was finally the best one. The final code looks like this
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username=(String)authentication.getPrincipal();
User user=null;
if(username!=null){
user=getUserRepository().findByUserName(username);
if(user!=null){
if(user.getEnabled()!=0){
if((user.getUserDetail().getConfirmed()!=0)||((new Date().getTime()-user.getUserDetail().getRequestDate().getTime())/(1000 * 60 * 60 * 24))<=getUnconfirmedDays()){
if(getPasswordEncoder().isPasswordValid(user.getPassword(), (String)authentication.getCredentials(), user)){
user.authenticated=true;
user.getAuthorities();
} else {
throw new BadCredentialsException("Password incorrect");
}
}else{
throw new UserNotConfirmedAndTimeExceeded("User has not been cofirmed in the established time period");
}
}else{
throw new DisabledException("User is disabled");
}
}else{
throw new BadCredentialsException("User does not exist");
}
}else{
throw new AuthenticationCredentialsNotFoundException("No credentials found in context");
}
return user;
}
All exceptions are part of the spring security exception stack. This is, those custom exceptions inherit from some existing exception. Then, in your security controller you should check for security exceptions and treat them as desired. For example redirecting to different pages.
Hope this helps!
i think its better to use other method/properties of user detail object for this purpose.
like
isAccountNonExpired()
isAccountNonLocked()
isEnabled()
and if you want to display custom error message then use message properties as explained in this article

Categories