下面列出了怎么用java.security.Principal的API类实例代码及写法,或者点击链接到github查看源代码。
private WebServiceContext createWebServiceContextMock(String expectedIP,
String expectedUser) {
requestMock = mock(HttpServletRequest.class);
when(requestMock.getRemoteAddr()).thenReturn(expectedIP);
Principal principalMock = mock(Principal.class);
when(principalMock.getName()).thenReturn(expectedUser);
MessageContext msgContextMock = mock(MessageContext.class);
when(msgContextMock.get(anyString())).thenReturn(requestMock);
WebServiceContext wsContextMock = mock(WebServiceContext.class);
when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);
return wsContextMock;
}
public static Subject loginUsingKeytab(final Set<String> principalAsStrings, final Path keytabPath, final boolean initiator) throws LoginException {
final Set<Principal> principals = new HashSet<Principal>();
for(String p: principalAsStrings) {
principals.add(new KerberosPrincipal(p));
}
final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
final Configuration conf = useKeytab("*", keytabPath, initiator);
final String confName = "KeytabConf";
final LoginContext loginContext = new LoginContext(confName, subject, null, conf);
loginContext.login();
return loginContext.getSubject();
}
@DeleteMapping("/event/{eventId}/additional-services/{additionalServiceId}")
@Transactional
public ResponseEntity<String> remove(@PathVariable("eventId") int eventId, @PathVariable("additionalServiceId") int additionalServiceId, Principal principal) {
return eventRepository.findOptionalById(eventId)
.map(event -> additionalServiceRepository.getOptionalById(additionalServiceId, eventId)
.map(as -> {
log.debug("{} is deleting additional service #{}", principal.getName(), additionalServiceId);
int deletedTexts = additionalServiceTextRepository.deleteAdditionalServiceTexts(additionalServiceId);
log.debug("deleted {} texts", deletedTexts);
//TODO add configuration fields and values
additionalServiceRepository.delete(additionalServiceId, eventId);
log.debug("additional service #{} successfully deleted", additionalServiceId);
return ResponseEntity.ok("OK");
})
.orElseGet(() -> new ResponseEntity<>("additional service not found", HttpStatus.NOT_FOUND)))
.orElseGet(() -> new ResponseEntity<>("event not found", HttpStatus.NOT_FOUND));
}
@Test
public void authenticateShouldReturnNullWhenNoMatchingUserExists() throws AuthenticationException {
final Principal principalMock = mock(Principal.class);
when(principalMock.getName())
.thenReturn("username");
final String token = new JsonWebToken().createToken(principalMock, null, IdentityProvider.LOCAL);
final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
.thenReturn(Collections.singletonList("Bearer " + token));
final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);
assertThat(authService.authenticate()).isNull();
}
private SecurityContext createSecurityContext(Message msg,
SamlAssertionWrapper samlAssertion) {
String roleAttributeName =
(String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
if (roleAttributeName == null || roleAttributeName.length() == 0) {
roleAttributeName = WSS4JInInterceptor.SAML_ROLE_ATTRIBUTENAME_DEFAULT;
}
ClaimCollection claims =
SAMLUtils.getClaims(samlAssertion);
Set<Principal> roles =
SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);
SAMLSecurityContext context =
new SAMLSecurityContext(new SAMLTokenPrincipalImpl(samlAssertion), roles, claims);
context.setIssuer(SAMLUtils.getIssuer(samlAssertion));
context.setAssertionElement(SAMLUtils.getAssertionElement(samlAssertion));
return context;
}
/**
* Return the Principal associated with the specified username and
* credentials, if one exists in the user data store; otherwise return null.
*/
@Override
public Principal authenticate(String username, String credentials) {
GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
if (null != principal) {
try {
if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
principal = null;
}
} catch (CannotPerformOperationException | InvalidHashException e) {
LOGR.log(Level.WARNING, e.getMessage());
principal = null;
}
}
return principal;
}
private WebServiceContext createWebServiceContextMock(String expectedIP,
String expectedUser) {
requestMock = mock(HttpServletRequest.class);
when(requestMock.getRemoteAddr()).thenReturn(expectedIP);
Principal principalMock = mock(Principal.class);
when(principalMock.getName()).thenReturn(expectedUser);
MessageContext msgContextMock = mock(MessageContext.class);
when(msgContextMock.get(anyString())).thenReturn(requestMock);
WebServiceContext wsContextMock = mock(WebServiceContext.class);
when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);
return wsContextMock;
}
@MessageMapping("/create/playqueue")
@SendToUser(broadcast = false)
public int createPlaylistForPlayQueue(Principal p, Integer playerId) throws Exception {
Player player = playerService.getPlayerById(playerId);
Locale locale = localeResolver.resolveLocale(p.getName());
DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(locale);
Instant now = Instant.now();
Playlist playlist = new Playlist();
playlist.setUsername(p.getName());
playlist.setCreated(now);
playlist.setChanged(now);
playlist.setShared(false);
playlist.setName(dateFormat.format(now.atZone(ZoneId.systemDefault())));
playlistService.createPlaylist(playlist);
playlistService.setFilesInPlaylist(playlist.getId(), player.getPlayQueue().getFiles());
return playlist.getId();
}
/**
* Returns metrics for the current users queries that are identified by the id
*
* @param id
*
* @return datawave.webservice.result.QueryMetricListResponse
*
* @RequestHeader X-ProxiedEntitiesChain use when proxying request for user, by specifying a chain of DNs of the identities to proxy
* @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
* @HTTP 200 success
* @HTTP 500 internal server error
*/
@GET
@POST
@Path("/id/{id}")
@Interceptors({RequiredInterceptor.class, ResponseInterceptor.class})
public BaseQueryMetricListResponse query(@PathParam("id") @Required("id") String id) {
// Find out who/what called this method
DatawavePrincipal dp = null;
Principal p = ctx.getCallerPrincipal();
String user = p.getName();
if (p instanceof DatawavePrincipal) {
dp = (DatawavePrincipal) p;
user = dp.getShortName();
}
return queryHandler.query(user, id, dp);
}
public void push(final Principal principal, final Object credential,
final Subject subject, final String securityDomain)
{
AccessController.doPrivileged(
new PrivilegedAction<Object>()
{
public Object run()
{
//SecurityAssociation.pushSubjectContext(subject, principal, credential);
SecurityContext sc = SecurityContextAssociation.getSecurityContext();
if(sc == null)
{
try
{
sc = SecurityContextFactory.createSecurityContext(principal, credential,
subject, securityDomain);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
SecurityContextAssociation.setSecurityContext(sc);
return null;
}
}
);
}
/**
* Receives the messages from clients and sends them to ActiveMQ.
*
* @param message the message to send, encapsulated in a wrapper
*/
@RequestMapping(value = "/send", method = RequestMethod.POST, consumes = "application/json")
public void sendMessage(@RequestBody MessageDTO message, Principal currentUser) {
// send any message sent by clients to a queue called rt_messages
message.from = currentUser.getName();
camelContext.createProducerTemplate().sendBody("activemq:rt_messages", message);
}
@Override public Void run() {
Set<Principal> principals = new HashSet<>();
Set<Object> publicCredentials = new HashSet<>();
Set<Object> privateCredentials = new HashSet<>();
principals.add(principal);
Subject subject = new Subject(true,
principals,
publicCredentials,
privateCredentials);
Subject.doAsPrivileged(subject, action, null);
return null;
}
private RoleGroup getCurrentRoles(Principal principal)
{
//Check that the caller is authenticated to the current thread
Subject subject = SubjectActions.getActiveSubject();
//Deal with the security context
SecurityContext sc = SubjectActions.getSecurityContext();
if(sc == null)
{
sc = new JBossSecurityContext(securityDomain);
SubjectActions.setSecurityContext(sc);
}
return getCurrentRoles(principal,subject,sc);
}
@Test
void testAuthenticateKeystoreEC() throws Exception {
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getClass().getResourceAsStream("/keystore.jks"), passphrase);
final String token = buildEcToken(ks.getKey("trellis-ec", passphrase), "trellis-ec");
final Authenticator authenticator = new FederatedJwtAuthenticator(ks,
singletonList("trellis-ec"));
final Principal p = authenticator.authenticate(token);
assertNotNull(p, "Missing principal!");
assertEquals("https://people.apache.org/~acoburn/#i", p.getName(), "Incorrect webid!");
}
@WebMethod(operationName = "findParametersInternal")
public Parameters findParameters(Internal internal, SimulatorInst simulator) {
Principal cPrincipal = getCallerPrincipal();
ParametersContainer pc1 = internal.getParametersContainer();
List<Parameters> plist = pc1.getParameters();
for (Parameters parameters : plist) {
if (parameters.getSimulator().getId() == simulator.getId()) {
return parameters;
}
}
return null;
}
static <P extends Principal> P getSingletonPrincipal(final Subject authSubject,
final boolean isPrincipalOptional,
final Class<P> principalClazz)
{
if (authSubject == null)
{
throw new IllegalArgumentException("No authenticated subject.");
}
final Set<P> principals = authSubject.getPrincipals(principalClazz);
int numberOfAuthenticatedPrincipals = principals.size();
if(numberOfAuthenticatedPrincipals == 0 && isPrincipalOptional)
{
return null;
}
else
{
if (numberOfAuthenticatedPrincipals != 1)
{
throw new IllegalArgumentException(
String.format(
"Can't find single %s in the authenticated subject. There were %d "
+ "%s principals out of a total number of principals of: %s",
principalClazz.getSimpleName(),
numberOfAuthenticatedPrincipals,
principalClazz.getSimpleName(),
authSubject.getPrincipals()));
}
return principals.iterator().next();
}
}
@PostMapping("del_message")
protected String delMessage(
@RequestParam String millis,
Principal principal) {
if(millis != null) {
messageService.deleteMessage(principal.getName(), millis);
}
return REDIRECT_MEMBER_PATH;
}
@Test
public void testCognitoCustomAuthorizerPrincipal() {
Map<String, Object> authorizerDate = new HashMap<>();
authorizerDate.put("principalId", "123");
authorizerDate.put("custom:value", "blub");
Principal principal = testPrincipal(authorizerDate);
assertTrue(principal instanceof CustomAuthorizerPrincipal);
CustomAuthorizerPrincipal cognitoCustomPrincipal = (CustomAuthorizerPrincipal) principal;
assertEquals("123", cognitoCustomPrincipal.getName());
assertEquals("123", cognitoCustomPrincipal.getClaims().getPrincipalId());
assertEquals("blub", cognitoCustomPrincipal.getClaims().getAllClaims().get("custom:value"));
}
@Secured({"ROLE_ADMIN"})
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
@Valid Department department,
BindingResult bindingResult,
Principal principal,
Model uiModel,
HttpServletRequest httpServletRequest) {
log.info("update(): handles PUT");
try{
User user = userService.user_findByLogin(principal.getName());
if(proceed != null){
if (bindingResult.hasErrors()) {
populateEditForm(uiModel, department,user);
return "security/departments/update";
}
if (surveySettingsService.department_findByName(department.getName()) != null &&
!surveySettingsService.department_findByName(department.getName()).getId().equals(department.getId())) {
bindingResult.rejectValue("name", "field_unique");
populateEditForm(uiModel, department,user);
return "security/departments/update";
}
uiModel.asMap().clear();
department = surveySettingsService.department_merge(department);
return "redirect:/security/departments/" + encodeUrlPathSegment(department.getId().toString(), httpServletRequest);
}else{
return "redirect:/security/departments?page=1&size=10";
}
} catch (Exception e) {
log.error(e.getMessage(),e);
throw (new RuntimeException(e));
}
}
private static Principal getPeerPrincipal(SSLSession session)
throws SSLPeerUnverifiedException {
Principal principal;
try {
principal = session.getPeerPrincipal();
} catch (AbstractMethodError e) {
// if the JSSE provider does not support it, return null, since
// we need it only for Kerberos.
principal = null;
}
return principal;
}
public String getAuthorizationId() {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
Set<Principal> principals = subject.getPrincipals();
Iterator<Principal> i = principals.iterator();
StringBuffer buffer = new StringBuffer();
while(i.hasNext()) {
Principal p = i.next();
buffer.append(p.getName());
if(i.hasNext())
buffer.append(" ");
}
return buffer.toString();
}
private static HttpClient buildSpengoHttpClient() {
HttpClientBuilder builder = HttpClientBuilder.create();
Lookup<AuthSchemeProvider> authSchemeRegistry
= RegistryBuilder.<AuthSchemeProvider>create().register(
AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getPassword() {
return null;
}
});
builder.setDefaultCredentialsProvider(credentialsProvider);
// Avoid output WARN: Cookie rejected
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.build();
builder.setDefaultRequestConfig(globalConfig);
CloseableHttpClient httpClient = builder.build();
return httpClient;
}
@Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"})
@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
public String updateForm(@PathVariable("id") Long questionId,
Principal principal,
HttpServletRequest httpServletRequest,
Model uiModel) {
log.info("updateForm(): questionId=" + questionId);
try{
String login = principal.getName();
User user = userService.user_findByLogin(login);
Question question = surveySettingsService.question_findById(questionId);
//Check if the user is authorized
if(!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(), user) &&
!securityService.userBelongsToDepartment(question.getPage().getSurveyDefinition().getDepartment().getId(), user)) {
log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr());
return "accessDenied";
}
SortedSet<QuestionColumnLabel> ColumnLabels = question.getColumnLabels();
log.info("initial set size" + ColumnLabels.size());
for (int i =1; i<=EMPTY_OPTIONS_COUNT; i++){
log.info("adding to set" + i);
ColumnLabels.add(new QuestionColumnLabel(question,(short) (question.getColumnLabels().size() + i)));
}
question.setColumnLabels(ColumnLabels);
uiModel.addAttribute("question", question);
return "settings/questionCols/update";
} catch (Exception e) {
log.error(e.getMessage(),e);
throw (new RuntimeException(e));
}
}
private void checkPrincipalsMatch(Subject subject) {
boolean nameFound = false;
boolean[] rolesFound = new boolean[ROLE_NAMES.size()];
for (int i = 0; i < rolesFound.length; ++i) {
rolesFound[i] = false;
}
for (Principal currentPrincipal : subject.getPrincipals()) {
if (currentPrincipal instanceof UserPrincipal) {
if (currentPrincipal.getName().equals(USER_NAME)) {
if (!nameFound) {
nameFound = true;
} else {
fail("UserPrincipal found twice.");
}
} else {
fail("Unknown UserPrincipal found.");
}
} else if (currentPrincipal instanceof RolePrincipal) {
int principalIdx = ROLE_NAMES.indexOf(((RolePrincipal) currentPrincipal).getName());
if (principalIdx < 0) {
fail("Unknown RolePrincipal found.");
}
if (!rolesFound[principalIdx]) {
rolesFound[principalIdx] = true;
} else {
fail("RolePrincipal found twice.");
}
} else {
fail("Unknown Principal type found.");
}
}
}
public Principal remotePrincipal() {
final WarpSocketContext warpSocketContext = this.warpSocketContext;
if (warpSocketContext != null) {
return warpSocketContext.remotePrincipal();
} else {
return null;
}
}
@Override
public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) {
final byte[] decodedSecretKey = Base64.getDecoder().decode(secretKey);
final Key secretKeyKey = new SecretKeySpec(decodedSecretKey, 0, decodedSecretKey.length, this.getSignatureAlgorithm().toString());
return new JsonWebTokenAuthFilter.Builder<>()
.setAuthenticator(new JsonWebTokenAuthenticator(secretKeyKey, this.getSignatureAlgorithm()))
.setAuthorizer(new PermitAllAuthorizer())
.buildAuthFilter();
}
@PostMapping
public Mono<Tweet> save(Principal principal, @RequestBody Tweet tweet) {
Mono<User> user = userService.getUserByScreenName(principal.getName());
return user.flatMap(u -> {
tweet.setTweetUser(u);
return tweetService.save(tweet);
});
}
protected Principal getPrincipal(Principal originalPrincipal, Subject subject) {
Principal[] ps = subject.getPrincipals().toArray(new Principal[subject.getPrincipals().size()]);
if (ps != null && ps.length > 0
&& !DefaultSecurityContext.isGroupPrincipal(ps[0])) {
return ps[0];
}
return originalPrincipal;
}
public Properties getValidCredentials(Principal principal) {
String userName = principal.getName();
if (DummyAuthenticator.testValidName(userName)) {
Properties props = new Properties();
props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
return props;
}
else {
throw new IllegalArgumentException("Dummy: [" + userName
+ "] is not a valid user");
}
}
/**
* Returns the server's principal, or throws SSLPeerUnverifiedException
* if the server did not authenticate.
*/
Principal getPeerPrincipal()
throws SSLPeerUnverifiedException
{
if (cachedResponse != null) {
return ((SecureCacheResponse)cachedResponse).getPeerPrincipal();
}
if (http == null) {
throw new IllegalStateException("connection not yet open");
} else {
return (((HttpsClient)http).getPeerPrincipal());
}
}