Java Code Examples for org.springframework.security.authentication.UsernamePasswordAuthenticationToken#getPrincipal()

The following examples show how to use org.springframework.security.authentication.UsernamePasswordAuthenticationToken#getPrincipal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractLoginTest.java    From kafka-webview with MIT License 5 votes vote down vote up
protected void validateAuthenticated(
    final MvcResult result,
    final String expectedUsername,
    final long expectedUserId,
    final Collection<String> expectedRoles
) {
    // Validate session is valid
    final MockHttpSession session = (MockHttpSession) result.getRequest().getSession();
    assertNotNull("Session should not be null", session);
    assertTrue("Session should be new", session.isNew());
    assertFalse("sesison should be valid", session.isInvalid());

    // Pull out context
    final SecurityContext securityContext = (SecurityContext) session.getValue("SPRING_SECURITY_CONTEXT");
    assertNotNull("Should be authenticated", securityContext);
    final UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) securityContext.getAuthentication();
    assertNotNull("Should be authenticated", authenticationToken);

    // Verify we have the correct roles
    expectedRoles.forEach((expectedRole) -> {
        assertTrue("Should have user role", authenticationToken.getAuthorities().contains(new SimpleGrantedAuthority(expectedRole)));
    });
    assertEquals("Should have no extra roles", expectedRoles.size(), authenticationToken.getAuthorities().size());

    final CustomUserDetails customUserDetails = (CustomUserDetails) authenticationToken.getPrincipal();
    expectedRoles.forEach((expectedRole) -> {
        assertTrue("Should have user role", customUserDetails.getAuthorities().contains(new SimpleGrantedAuthority(expectedRole)));
    });
    assertEquals("Should have no extra roles", expectedRoles.size(), customUserDetails.getAuthorities().size());

    assertEquals("LDAP Users should have userId", expectedUserId, customUserDetails.getUserId());
    assertEquals("Should have username", expectedUsername, customUserDetails.getUsername());
}
 
Example 2
Source File: EventsController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@GetMapping("/my")
    public ModelAndView myEvents(@AuthenticationPrincipal UsernamePasswordAuthenticationToken upat) {
        CalendarUser currentUser = (CalendarUser)upat.getPrincipal();

        return myEvents(currentUser);
//        Integer currentUserId = currentUser.getId();
//        ModelAndView result = new ModelAndView("events/my", "events", calendarService.findForUser(currentUserId));
//        result.addObject("currentUser", currentUser);
//        return result;
    }
 
Example 3
Source File: EventsController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@GetMapping("/my")
    public ModelAndView myEvents(@AuthenticationPrincipal UsernamePasswordAuthenticationToken upat) {
        CalendarUser currentUser = (CalendarUser)upat.getPrincipal();

        return myEvents(currentUser);
//        Integer currentUserId = currentUser.getId();
//        ModelAndView result = new ModelAndView("events/my", "events", calendarService.findForUser(currentUserId));
//        result.addObject("currentUser", currentUser);
//        return result;
    }
 
Example 4
Source File: SecurityContextAuthenticator.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private boolean isAdmin(SecurityContext context) {
    if (context.getAuthentication() == null) {
        return false;
    }

    Authentication authentication = context.getAuthentication();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        if (token.getPrincipal() instanceof String) {
            return token.getPrincipal().equals(config.getAdminLogin()) &&
                    token.getCredentials().equals(config.getAdminPassword());
        }
    }

    Object principal = authentication.getPrincipal();

    if (!(principal instanceof User)) {
        return false;
    }

    User user = (User) principal;
    if (user == null) {
        return false;
    }

    Collection<GrantedAuthority> authorities = user.getAuthorities();
    if (authorities == null) {
        return false;
    }

    return authorities.contains(ROLE_ADMIN.authority());
}
 
Example 5
Source File: GateWayController.java    From poseidon with Apache License 2.0 4 votes vote down vote up
public String curUser(HttpEntity entity) {
	UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) SecurityContextHolder
			.getContext().getAuthentication();
	return (String) token.getPrincipal();
}
 
Example 6
Source File: ConnectorAuthStrategyBasicAuthTest.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@Test(expected = BadCredentialsException.class)
public void testAuthBasicBad() throws Exception {

    final AuthenticationManager manager = this.context.mock(AuthenticationManager.class);
    final HttpServletRequest request = this.context.mock(HttpServletRequest.class);

    final ConnectorAuthStrategyBasicAuth auth = new ConnectorAuthStrategyBasicAuth();

    auth.setAuthenticationManager(manager);

    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("üsernäme", "pä$sw()rd");
    final String basic = token.getPrincipal() + ":" + token.getCredentials();
    final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes(StandardCharsets.UTF_8));


    this.context.checking(new Expectations() {{
        allowing(request).getHeader("Authorization"); will(returnValue("Basic " + new String(encodedBytes)));
        allowing(manager).authenticate(token); will(throwException(new BadCredentialsException("bad")));
    }});

    auth.authenticated(request);

}
 
Example 7
Source File: ConnectorAuthStrategyBasicAuthTest.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@Test
public void testAuthBasicValidUTF8() throws Exception {

    final AuthenticationManager manager = this.context.mock(AuthenticationManager.class);
    final HttpServletRequest request = this.context.mock(HttpServletRequest.class);

    final ConnectorAuthStrategyBasicAuth auth = new ConnectorAuthStrategyBasicAuth();

    auth.setAuthenticationManager(manager);


    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("üsernäme", "pä$sw()rd");
    final String basic = token.getPrincipal() + ":" + token.getCredentials();
    final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes(StandardCharsets.UTF_8));


    this.context.checking(new Expectations() {{
        allowing(request).getHeader("Authorization"); will(returnValue("Basic " + new String(encodedBytes)));
        allowing(manager).authenticate(token); will(returnValue(token));
    }});

    assertTrue(auth.authenticated(request));

}
 
Example 8
Source File: ConnectorAuthStrategyBasicAuthTest.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@Test
public void testAuthBasicValidRegular() throws Exception {

    final AuthenticationManager manager = this.context.mock(AuthenticationManager.class);
    final HttpServletRequest request = this.context.mock(HttpServletRequest.class);

    final ConnectorAuthStrategyBasicAuth auth = new ConnectorAuthStrategyBasicAuth();

    auth.setAuthenticationManager(manager);


    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("username", "pa$sw()rd");
    final String basic = token.getPrincipal() + ":" + token.getCredentials();
    final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes(StandardCharsets.UTF_8));


    this.context.checking(new Expectations() {{
        allowing(request).getHeader("Authorization"); will(returnValue("Basic " + new String(encodedBytes)));
        allowing(manager).authenticate(token); will(returnValue(token));
    }});

    assertTrue(auth.authenticated(request));

}