Example usage for org.springframework.security.core Authentication getPrincipal

List of usage examples for org.springframework.security.core Authentication getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:com.esquema.seguridad.AutenticacionPersonalizada.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    UsernamePasswordAuthenticationToken auth;
    String usuario = String.valueOf(authentication.getPrincipal());
    //System.out.println("Usuario..: " + usuario);

    String password = null;/* w w w. j  a v a  2  s  .c o m*/
    try {
        //password = encr.encr(authentication.getCredentials().toString());
        password = authentication.getCredentials().toString();
        //System.out.println("Passwordss..: " + password);

    } catch (Exception ex) {
        Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (usuario.isEmpty() && !password.isEmpty()) {
        throw new BadCredentialsException("Usuario no vlido");
    }

    if (password.isEmpty() && !usuario.isEmpty()) {
        throw new BadCredentialsException("Clave no vlida");
    }

    if (usuario.isEmpty() && password.isEmpty()) {
        throw new BadCredentialsException("Credenciales no vlidas");
    }

    //Llamado al mtodo encuentra. Est ms arriba.
    s_user usuarioBD = encuentra(usuario);

    if (usuarioBD.getEnabled() == 0) {
        throw new BadCredentialsException("El usuario [" + usuario.toUpperCase() + "] se encuentra bloqueado");
    }

    /*
    System.out.println("Clave de HTTPS..: " + clave);
    System.out.println("Resultado del query..: " + usuarioBD);
    System.out.println("Usuario BD..: " + usuarioBD.getUserlogin());
    System.out.println("Password BD..: " + usuarioBD.getPasswd());
    */

    if (usuarioBD.getIs_ldap() == 1) {
        try {
            ldapTemplate.afterPropertiesSet();
        } catch (Exception ex) {
            Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Perform the authentication.
        Filter filter = new EqualsFilter("sAMAccountName", usuario);

        if (!ldapTemplate.authenticate(env.getProperty("ldap.base"), filter.encode(), password)) {
            throw new BadCredentialsException("Clave o Usuario invlido");
        }
    } else {

        String clave = null;
        try {
            //create MD5 hash using the string: userlogin:passwd
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] b = (usuario + ":" + password).getBytes();
            //byte[] b = (password).getBytes();
            byte[] hash = md.digest(b);
            clave = Base64.encodeToString(hash, true);
        } catch (Exception ex) {
            Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (usuarioBD == null || (!clave.equals(usuarioBD.getPasswd()))) {
            throw new BadCredentialsException("Clave o Usuario invlido");
        }
    }

    /*
    System.out.println("Usuario BD..: " + usuarioBD.getUserlogin());
    System.out.println("Password BD..: " + usuarioBD.getPasswd());
    */
    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

    auth = new UsernamePasswordAuthenticationToken(usuario, password, grantedAuths);
    auth.setDetails(usuarioBD);

    return auth;
}

From source file:info.raack.appliancelabeler.security.HttpSessionAndDatabaseOAuthRemeberMeServices.java

public Map<String, OAuthConsumerToken> loadRememberedTokens(HttpServletRequest request,
        HttpServletResponse response) {//from  w  ww.  j a va2  s.  c  o  m
    // check httpsessionrememberme services first

    Map<String, OAuthConsumerToken> tokens = super.loadRememberedTokens(request, response);

    if (tokens != null) {
        logger.debug("Found existing oauth tokens in session");
        return tokens;
    } else {
        // haven't found any tokens yet - look in the database

        // ASSUMPTIONS - remember tokens is called with every token request (spring security oauth code), so any tokens in the session will also be in the database
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        String userId = null;
        if (auth != null && auth.isAuthenticated()) {
            if (auth instanceof RememberMeAuthenticationToken) {
                Object principal = auth.getPrincipal();
                if (principal instanceof OAuthUserDetails) {
                    logger.debug("Found existing oauth tokens in remember me persistence");
                    return ((OAuthUserDetails) principal).getOAuthTokens();
                } else if (principal instanceof String) {
                    logger.debug(
                            "Found user id in remember me persistence; grabbing oauth tokens from database");
                    return dataService.getOAuthTokensForUserId((String) principal);
                }
            } else if (auth instanceof OAuthAutomaticAuthenticationToken) {
                // user is already logged in via spring security
                logger.debug(
                        "Found user id in oauth automatic login token; grabbing oauth tokens from database");
                return dataService.getOAuthTokensForUserId((String) auth.getPrincipal());
            }
        }
        return null;
    }
}

From source file:controller.LinkController.java

public String obtenerMenu(String aplicacion) {

    int nroApp;//ww  w . j  a v  a  2  s  .  co  m
    nroApp = Integer.parseInt(aplicacion);
    String retorno = "";

    usuario = new Usuario();
    menuView = new ArrayList<>();
    menuViewResponsive = new ArrayList<>();
    System.out.print("EL NUMERO DE LA APLICACION: " + nroApp + " Usuario:" + usuario.getCod_usuario());

    SecurityContext context = SecurityContextHolder.getContext();
    if (context instanceof SecurityContext) {
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof Authentication) {
            usuario.setUsername(((User) authentication.getPrincipal()).getUsername());
            usuario.setPassword(((User) authentication.getPrincipal()).getPassword());
            usuario = dao_usuario.findUsuario(usuario);
            int sw = 0;

            List<Operacion> operacion = new ArrayList<>();
            operacion = dao_operacion.findAll(usuario.getCod_usuario(), nroApp); //EL Parametro nroApp es el ID DE LA tabla APLICACION

            menu_dinamic(operacion);

            for (Operacion item : operacion) {
                if (item.getCod_opera_padre() == 0) {
                    System.out.println("codigo padre:" + item.getCod_opera() + "-" + operacion.size()
                            + " ,CODIGO APP: " + item.getAplicacion_id_app());
                    List<Operacion> sub = submenu(item.getCod_opera(), operacion);
                    menuView.add(new MenuView(item.getCod_opera(), item.getCod_opera_padre(),
                            item.getDescripcion(), item.getHref(), item.getIcon(), sub));
                    for (Operacion subitem : sub) {
                        menuViewResponsive
                                .add(new MenuView(subitem.getCod_opera(), subitem.getCod_opera_padre(),
                                        subitem.getDescripcion(), subitem.getHref(), subitem.getIcon(), null));
                    }
                }
            }
        }
    }

    FacesContext contextMenu = FacesContext.getCurrentInstance();
    Map<String, String> map = contextMenu.getExternalContext().getRequestParameterMap();
    String dato = map.get("aplicacion");
    System.out.println("href" + dato);
    String link = "";

    if (dato.equals("denuncias")) {
        //link = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("denuncias");            
        System.out.println("Aplicacion " + dato);
        retorno = "/denuncia/denuncia.xhtml?faces-redirect=true";
    }
    if (dato.equals("ruv")) {
        //link = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("denuncias");            
        System.out.println("Aplicacion " + dato);
        retorno = "detalle?faces-redirect=true";
    }
    if (dato.equals("indicadores")) {
        //link = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("denuncias");            
        System.out.println("Aplicacion " + dato);
        retorno = "/indicadores/indicadores.xhtml?faces-redirect=true";
    }
    if (dato.equals("acceso")) {
        //link = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("denuncias");            
        System.out.println("Aplicacion " + dato);
        retorno = "/acceso/usuariosListado.xhtml?faces-redirect=true";
    }

    return (retorno);
}

From source file:waffle.spring.ImpersonateTests.java

/**
 * Test impersonate disabled.// www  .j a v a  2s.co  m
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Test
public void testImpersonateDisabled() throws IOException, ServletException {

    Assertions.assertNotEquals("Current user shouldn't be the test user prior to the test",
            MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName());
    final SimpleHttpRequest request = new SimpleHttpRequest();
    request.setMethod("GET");
    final String userHeaderValue = MockWindowsAccount.TEST_USER_NAME + ":" + MockWindowsAccount.TEST_PASSWORD;
    final String basicAuthHeader = "Basic "
            + Base64.getEncoder().encodeToString(userHeaderValue.getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", basicAuthHeader);
    final SimpleHttpResponse response = new SimpleHttpResponse();
    final RecordUserNameFilterChain filterChain = new RecordUserNameFilterChain();

    this.filter.setImpersonate(false);
    this.filter.doFilter(request, response, filterChain);

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Assertions.assertTrue(authentication.isAuthenticated(), "Test user should be authenticated");

    final Principal principal = (Principal) authentication.getPrincipal();
    assertThat(principal).isInstanceOf(WindowsPrincipal.class);
    final WindowsPrincipal windowsPrincipal = (WindowsPrincipal) principal;
    try {
        Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, filterChain.getUserName(),
                "Test user should not be impersonated");
        Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName(),
                "Impersonation context should have been reverted");
    } finally {
        windowsPrincipal.getIdentity().dispose();
    }
}

From source file:waffle.spring.ImpersonateTests.java

/**
 * Test impersonate enabled.// w  w  w .  j a v  a 2s  .c  o m
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Test
public void testImpersonateEnabled() throws IOException, ServletException {

    Assertions.assertNotEquals("Current user shouldn't be the test user prior to the test",
            MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName());

    final SimpleHttpRequest request = new SimpleHttpRequest();
    request.setMethod("GET");
    final String userHeaderValue = MockWindowsAccount.TEST_USER_NAME + ":" + MockWindowsAccount.TEST_PASSWORD;
    final String basicAuthHeader = "Basic "
            + Base64.getEncoder().encodeToString(userHeaderValue.getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", basicAuthHeader);

    final SimpleHttpResponse response = new SimpleHttpResponse();
    final RecordUserNameFilterChain filterChain = new RecordUserNameFilterChain();

    this.filter.setImpersonate(true);
    this.filter.doFilter(request, response, filterChain);

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Assertions.assertTrue(authentication.isAuthenticated(), "Test user should be authenticated");

    final Principal principal = (Principal) authentication.getPrincipal();
    assertThat(principal).isInstanceOf(AutoDisposableWindowsPrincipal.class);
    final AutoDisposableWindowsPrincipal windowsPrincipal = (AutoDisposableWindowsPrincipal) principal;
    try {
        Assertions.assertEquals(MockWindowsAccount.TEST_USER_NAME, filterChain.getUserName(),
                "Test user should be impersonated");
        Assertions.assertNotEquals(MockWindowsAccount.TEST_USER_NAME, Advapi32Util.getUserName(),
                "Impersonation context should have been reverted");
    } finally {
        windowsPrincipal.getIdentity().dispose();
    }
}

From source file:org.openmhealth.dsu.controller.DataPointController.java

public String getEndUserId(Authentication authentication) {
    return ((EndUserUserDetails) authentication.getPrincipal()).getUsername();
}

From source file:org.zkybase.kite.guard.RateLimitingThrottleTemplate.java

private Object getPrincipal() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication auth = context.getAuthentication();

    // FIXME There's probably a better way to detect anonymous auth.
    if (auth == null || auth instanceof AnonymousAuthenticationToken) {
        log.debug("Authentication required");
        throw new UnauthenticatedException();
    }/*from  www  .j  a  v  a  2s  . c o  m*/

    return auth.getPrincipal();
}

From source file:com.utest.dao.AuditTrailInterceptor.java

private Integer getCurrentUserId() {
    final SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = null;
    if (ctx != null) {
        auth = ctx.getAuthentication();/*from www .  j av a 2  s. c  o  m*/
    }
    return ((AuthenticatedUserInfo) auth.getPrincipal()).getLoggedInUserId();
}

From source file:se.vgregion.urlservice.controllers.BookmarkController.java

private Owner getUser(Authentication authentication) {
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            String userName = ((org.springframework.security.core.userdetails.User) principal).getUsername();

            return urlServiceService.getUser(userName);
        } else {//from  w  w  w .j a v a  2s  . co m
            return null;
        }
    } else {
        return null;
    }
}