b4f.seguridad.SecurityAuthenticator.java Source code

Java tutorial

Introduction

Here is the source code for b4f.seguridad.SecurityAuthenticator.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package b4f.seguridad;

import b4f.modelos.Usuario;
import b4f.util.JwtToken;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.SimplePrincipalCollection;

public class SecurityAuthenticator implements Authenticator {

    private static final boolean DEBUG = true;

    @Override
    public AuthenticationInfo authenticate(AuthenticationToken at) throws AuthenticationException {

        if (DEBUG) {
            System.out.println("[SECURITY AUTHENTICATOR] Autenticando: " + at);
        }

        //SE ACCEDI CON UN JWT TOKEN
        if (at instanceof JwtToken) {
            JwtToken authToken = (JwtToken) at;
            if (authToken.getToken() != null && !authToken.getToken().equals("")) {

                if (!authToken.validar()) {
                    throw new AccountException("Token invalido.");
                }

                try {
                    Usuario user = UsersManager.getUser(authToken.getUser());
                    if (user == null)
                        throw new Exception("Token invalido");

                    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo();
                    authenticationInfo.setPrincipals(new SimplePrincipalCollection(user, user.getUsuario()));
                    return authenticationInfo;
                } catch (Exception ex) {
                    Logger.getLogger(ShiroAuthorizingRealm.class.getName()).log(Level.SEVERE, null, ex);
                    throw new AuthenticationException(ex.getMessage());
                }

            } else {
                throw new AccountException("Token invalido.");
            }
        }

        DefaultSecurityManager dsm = new DefaultSecurityManager(getRealm());
        AuthenticationInfo authenticationInfo = dsm.authenticate(at);
        if (DEBUG) {
            System.out.println("[SECURITY AUTHENTICATOR] " + authenticationInfo);
        }
        return authenticationInfo;

    }

    private Realm getRealm() {
        return new ShiroAuthorizingRealm();
    }

}