org.springframework.security.core.context.SecurityContextHolder Java Examples

The following examples show how to use org.springframework.security.core.context.SecurityContextHolder. 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: JWTFilterTest.java    From jhipster-microservices-example with Apache License 2.0 7 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example #2
Source File: AccessTokenUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static Optional<String> getAccessTokenFromSecurityContext() {
    SecurityContext securityContext = SecurityContextHolder.getContext();

    Authentication authentication = securityContext.getAuthentication();
    if (authentication instanceof OAuth2Authentication) {
        Object userDetails = ((OAuth2Authentication) authentication).getUserAuthentication().getDetails();
        if (userDetails != null) {
            try {
                final Map details = (Map) userDetails;
                return Optional.ofNullable(((String) details.get(ACCESS_TOKEN)));
            } catch (ClassCastException e) {

                return Optional.empty();
            }
        } else {

            return Optional.empty();
        }
    }

    return Optional.empty();
}
 
Example #3
Source File: UserJWTController.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());

    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException exception) {
        return new ResponseEntity<>(exception.getLocalizedMessage(), HttpStatus.UNAUTHORIZED);
    }
}
 
Example #4
Source File: SpringSecurityCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void checkCurrentToken() {
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
            checkPrincipalFromCookie();
    if (principal != null) {
        final RefreshableKeycloakSecurityContext securityContext =
                principal.getKeycloakSecurityContext();
        KeycloakSecurityContext current = ((OIDCHttpFacade) facade).getSecurityContext();
        if (current != null) {
            securityContext.setAuthorizationContext(current.getAuthorizationContext());
        }
        final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
        final OidcKeycloakAccount account =
                new SimpleKeycloakAccount(principal, roles, securityContext);
        SecurityContextHolder.getContext()
                .setAuthentication(new KeycloakAuthenticationToken(account, false));
    } else {
        super.checkCurrentToken();
    }
    cookieChecked = true;
}
 
Example #5
Source File: FrontendSmokeTest.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@Test
public void should_delete_network() throws Exception {
    UserVO user = new UserVO();
    user.setLogin(RandomStringUtils.randomAlphabetic(10));
    user.setRole(UserRole.ADMIN);
    user = userService.createUser(user, VALID_PASSWORD);

    String namePrefix = RandomStringUtils.randomAlphabetic(10);
    NetworkVO network = new NetworkVO();
    network.setName(namePrefix + randomUUID());
    network.setDescription("network description_" + randomUUID());

    NetworkVO created = networkService.create(network);
    assertThat(created.getId(), notNullValue());
    userService.assignNetwork(user.getId(), network.getId());

    final HivePrincipal principal = new HivePrincipal(user);
    SecurityContextHolder.getContext().setAuthentication(new HiveAuthentication(principal));

    boolean deleted = networkService.delete(created.getId(), true);
    assertTrue(deleted);

    created = networkDao.find(created.getId());
    assertThat(created, Matchers.nullValue());
}
 
Example #6
Source File: JwtAuthenticationFilter.java    From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    try{
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)){
            Long userId = tokenProvider.getUserIdFromJWT(jwt);

            UserDetails userDetails = customUserDetailsService.loadUserById(userId);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    } catch (Exception ex){
        LOGGER.error("Could not set user authentication in security context", ex);
    }

    filterChain.doFilter(request, response);
}
 
Example #7
Source File: QuestionAction.java    From ExamStack with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 添加试题
 * 
 * @param question
 * @return
 */
@RequestMapping(value = "/secure/question/question-add", method = RequestMethod.POST)
public @ResponseBody Message addQuestion(@RequestBody Question question) {

	UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	Message message = new Message();
	Gson gson = new Gson();
	question.setContent(gson.toJson(question.getQuestionContent()));
	question.setCreate_time(new Date());
	question.setCreator(userDetails.getUsername());
	try {
		questionService.addQuestion(question);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		message.setResult("error");
		message.setMessageInfo(e.getClass().getName());
		e.printStackTrace();
	}

	return message;
}
 
Example #8
Source File: ApplicationResource.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private void validateDeveloperHasAccessToApp(EntityBody app) {
    SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (sandboxEnabled) {
        @SuppressWarnings("unchecked")
        Map<String, Object> metaData = (Map<String, Object>) app.get("metaData");
        if (metaData != null) {
            String tenantId = (String) metaData.get("tenantId");
            if (tenantId != null && tenantId.equals(principal.getTenantId())) {
                return;
            }
        }
        throw new APIAccessDeniedException("Developer " + principal.getExternalId()
                + " does not share the same tenant as the creator of this app and cannot modify it.");
    } else {
        if (!(principal.getExternalId().equals(app.get(CREATED_BY)) || belongToSameSandboxTenant(app, principal.getSandboxTenant()))) {
            throw new APIAccessDeniedException("Developer " + principal.getExternalId()
                    + " is not the creator of this app and does not share same sandbox tenant as the creator hence cannot modify it.");
        }
    }
}
 
Example #9
Source File: UmsAdminServiceImpl.java    From mall-learning with Apache License 2.0 6 votes vote down vote up
@Override
public String login(String username, String password) {
    String token = null;
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        token = jwtTokenUtil.generateToken(userDetails);
    } catch (AuthenticationException e) {
        LOGGER.warn("登录异常:{}", e.getMessage());
    }
    return token;
}
 
Example #10
Source File: LdapAuthFilter.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Calls an external API to get the user profile using a given access token.
 * @param app the app where the user will be created, use null for root app
 * @param accessToken access token - in the case of LDAP this is should be "uid:password"
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException {
	UserAuthentication userAuth = null;
	if (accessToken != null && accessToken.contains(Config.SEPARATOR)) {
		String[] parts = accessToken.split(Config.SEPARATOR, 2);
		String username = parts[0];
		String password = parts[1];
		try {
			Authentication auth = new LDAPAuthentication(username, password).withApp(app);

			// set authentication in context to avoid warning message from SpringSecurityAuthenticationSource
			SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
					"anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
			Authentication ldapAuth = getAuthenticationManager().authenticate(auth);
			if (ldapAuth != null) {
				//success!
				userAuth = getOrCreateUser(app, ldapAuth);
			}
		} catch (Exception ex) {
			LOG.info("Failed to authenticate '{}' with LDAP server: {}", username, ex.getMessage());
		}
	}
	return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), false);
}
 
Example #11
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void initFeedbackAnonymous() throws Exception {
  SecurityContextHolder.getContext()
      .setAuthentication(new TestingAuthenticationToken("anonymous", null));

  List<String> adminEmails = Collections.singletonList("[email protected]");
  when(userService.getSuEmailAddresses()).thenReturn(adminEmails);
  verify(userService, never()).getUser("anonymous");

  mockMvcFeedback
      .perform(get(FeedbackController.URI))
      .andExpect(status().isOk())
      .andExpect(view().name("view-feedback"))
      .andExpect(model().attribute("adminEmails", adminEmails))
      .andExpect(model().attributeDoesNotExist("userName"))
      .andExpect(model().attributeDoesNotExist("userEmail"));
}
 
Example #12
Source File: _CustomSignInAdapter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example #13
Source File: JwtTokenFilter.java    From spring-boot-jwt with MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
  String token = jwtTokenProvider.resolveToken(httpServletRequest);
  try {
    if (token != null && jwtTokenProvider.validateToken(token)) {
      Authentication auth = jwtTokenProvider.getAuthentication(token);
      SecurityContextHolder.getContext().setAuthentication(auth);
    }
  } catch (CustomException ex) {
    //this is very important, since it guarantees the user is not authenticated at all
    SecurityContextHolder.clearContext();
    httpServletResponse.sendError(ex.getHttpStatus().value(), ex.getMessage());
    return;
  }

  filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example #14
Source File: JWTFilterTest.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example #15
Source File: AccountsController.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
public String accounts(Model model) {
	logger.debug("/accounts");
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("accounts: User logged in: " + currentUserName);
	    
	    try {
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	logger.debug("error retrieving accounts: " + e.getMessage());
	    	model.addAttribute("accountsRetrievalError",e.getMessage());
	    }
	}
	
	return "accounts";
}
 
Example #16
Source File: StaffToSubStudentSectionAssociationEntityValidatorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
    mockRepo = null;
    staffToStudentValidator = null;
    studentIds.clear();
    SecurityContextHolder.clearContext();
}
 
Example #17
Source File: UserJWTController.java    From tutorials with MIT License 5 votes vote down vote up
@PostMapping("/authenticate")
public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());

    Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
    String jwt = tokenProvider.createToken(authentication, rememberMe);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
}
 
Example #18
Source File: SysLogUtils.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取用户名称
 *
 * @return username
 */
private String getUsername() {
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (authentication == null) {
		return null;
	}
	return authentication.getName();
}
 
Example #19
Source File: PluginResourceImpl.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
@Override
public void register(PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization,
        @Suspended final AsyncResponse asyncResponse) {
    hiveValidator.validate(pluginUpdate);
    try {
        HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        pluginRegisterService.register(principal.getUser().getId(), pluginReqisterQuery, pluginUpdate, authorization)
                .thenAccept(asyncResponse::resume);
    } catch (ServiceUnavailableException e) {
        logger.warn(HEALTH_CHECK_FAILED);
        asyncResponse.resume(ResponseFactory.response(BAD_REQUEST,
                new ErrorResponse(BAD_REQUEST.getStatusCode(), HEALTH_CHECK_FAILED)));
    }
}
 
Example #20
Source File: GroovyScriptUtils.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
private static void addSecurityVariables(Map<String, Object> variables) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    variables.put(VARIABLE_AUTH_TOKEN, auth);

    // for backwards compatibility with Profile ...

    variables.put(VARIABLE_AUTH, null);
    variables.put(VARIABLE_PROFILE, null);

    if (auth != null && auth.getPrincipal() instanceof ProfileUser) {
        ProfileUser details = (ProfileUser) auth.getPrincipal();
        variables.put(VARIABLE_AUTH, details.getAuthentication());
        variables.put(VARIABLE_PROFILE, details.getProfile());
    }
}
 
Example #21
Source File: StaffLoginLogAction.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 员工登录日志列表
 * @param userId 员工Id
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/control/staffLoginLog/list") 
public String execute(ModelMap model,String userId,PageForm pageForm,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {	
	String _userId = "";//用户Id
	boolean issys = false;//是否是超级用户
	Object obj  =  SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
	if(obj instanceof SysUsers){
		issys = ((SysUsers)obj).isIssys();
		_userId =((SysUsers)obj).getUserId();
	}
	//调用分页算法代码
	PageView<StaffLoginLog> pageView = new PageView<StaffLoginLog>(settingService.findSystemSetting().getBackstagePageNumber(),pageForm.getPage(),10);
	//当前页
	int firstIndex = (pageForm.getPage()-1)*pageView.getMaxresult();;	
	if(userId != null && !"".equals(userId.trim())){
		if(issys == false && !_userId.equals(userId)){
			throw new SystemException("非超级管理员不允许查看其他成员登录记录");
		}
		QueryResult<StaffLoginLog> qr = staffService.findStaffLoginLogPage(userId, firstIndex, pageView.getMaxresult());
		if(qr != null && qr.getResultlist() != null && qr.getResultlist().size() >0){
			for(StaffLoginLog staffLoginLog : qr.getResultlist()){
				if(staffLoginLog.getIp() != null && !"".equals(staffLoginLog.getIp().trim())){
					staffLoginLog.setIpAddress(IpAddress.queryAddress(staffLoginLog.getIp()));
				}
			}
		}
		//将查询结果集传给分页List
		pageView.setQueryResult(qr);	
	}else{//如果接收到所属用户为空
		throw new SystemException("参数错误!");
	}
	model.addAttribute("pageView", pageView);

	return "jsp/staff/loginLogList";
}
 
Example #22
Source File: SysUserController.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/whoim")
@ResponseBody
public Object whoIm() {
    Set<String> urls = new HashSet<>();
    System.out.println(urls.toString());
    return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
 
Example #23
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example #24
Source File: AuthController.java    From microservices-sample-project with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/current")
public ResponseEntity<UserDetails> getCurrent() throws Exception{
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	
	String authenticatedUserName = authentication.getName();
	if(authenticatedUserName.equals("anonymousUser"))
		throw new UnAuthorizedAccessException(authenticatedUserName);
	else
		return makeResponse((UserDetails)authentication.getPrincipal());
}
 
Example #25
Source File: ExamPageAdmin.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 发布考试
 * 
 * @param model
 * @param request
 * @return
 */
@RequestMapping(value = "/admin/exam/model-test-add", method = RequestMethod.GET)
private String modelTestAddPage(Model model, HttpServletRequest request) {
	
	UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
		    .getAuthentication()
		    .getPrincipal();
	List<ExamPaper> examPaperList = examPaperService.getEnabledExamPaperList(userInfo.getUsername(), null);
	
	model.addAttribute("examPaperList", examPaperList);
	return "model-test-add";
}
 
Example #26
Source File: CommandHandlers.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
@HiveWebsocketAuth
@PreAuthorize("isAuthenticated() and hasPermission(#deviceId, 'UPDATE_DEVICE_COMMAND')")
public void processCommandUpdate(String deviceId, JsonObject request, WebSocketSession session) {
    HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    final Long id = gson.fromJson(request.get(COMMAND_ID), Long.class);
    final DeviceCommandUpdate commandUpdate = gson
            .fromJson(request.getAsJsonObject(COMMAND), DeviceCommandUpdate.class);

    logger.debug("command/update requested for session: {}. Device ID: {}. Command id: {}", session, deviceId, id);
    if (id == null) {
        logger.debug("command/update canceled for session: {}. Command id is not provided", session);
        throw new HiveException(Messages.COMMAND_ID_REQUIRED, SC_BAD_REQUEST);
    }

    if (deviceId == null) {
        throw new HiveException(DEVICE_ID_REQUIRED, SC_BAD_REQUEST);
    }

    DeviceVO deviceVO = deviceService.findByIdWithPermissionsCheck(deviceId, principal);
    if (deviceVO == null) {
        throw new HiveException(String.format(DEVICE_NOT_FOUND, deviceId), SC_NOT_FOUND);
    }

    commandService.findOne(id, deviceVO.getDeviceId())
            .thenAccept(optionalCommand -> {
                optionalCommand.map(deviceCommand -> commandService.update(deviceCommand, commandUpdate))
                        .orElseThrow(() -> new HiveException(String.format(COMMAND_NOT_FOUND, id), SC_NOT_FOUND));
            }).thenAccept(whenUpdated -> {
                logger.debug("command/update proceed successfully for session: {}. Device ID: {}. Command id: {}",
                        session, deviceId, id);
                clientHandler.sendMessage(request, new WebSocketResponse(), session);
            });
}
 
Example #27
Source File: SecurityService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
public PlatformUser getAuthorizedUser() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
        return (PlatformUser) authentication.getPrincipal();
    }
    return null;
}
 
Example #28
Source File: VoManagementServiceImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public VoLicenseAgreement acceptMyAgreement() throws Exception {

    final SecurityContext sc = SecurityContextHolder.getContext();
    final String username = sc != null && sc.getAuthentication() != null ? sc.getAuthentication().getName() : null;
    if (StringUtils.isNotBlank(username)) {
        managementService.grantRole(username, LICENSE_ROLE);
    }
    return getMyAgreement();

}
 
Example #29
Source File: MyAccessDeniedHandler.java    From spring-boot-shopping-cart with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest httpServletRequest,
                   HttpServletResponse httpServletResponse,
                   AccessDeniedException e) throws IOException, ServletException {

    Authentication auth
            = SecurityContextHolder.getContext().getAuthentication();

    if (auth != null) {
        logger.info(String.format("User '%s' attempted to access the protected URL: %s", auth.getName(), httpServletRequest.getRequestURI()));
    }

    httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");

}
 
Example #30
Source File: AuthorizationSupport.java    From front50 with Apache License 2.0 5 votes vote down vote up
public boolean hasRunAsUserPermission(final Pipeline pipeline) {
  List<String> runAsUsers =
      Optional.ofNullable(pipeline.getTriggers())
          .map(
              triggers ->
                  triggers.stream()
                      .map(it -> (String) it.get("runAsUser"))
                      .filter(Objects::nonNull)
                      .collect(Collectors.toList()))
          .orElse(Collections.emptyList());

  if (runAsUsers.isEmpty()) {
    return true;
  }

  final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

  return runAsUsers.stream()
      .noneMatch(
          runAsUser -> {
            if (!userCanAccessServiceAccount(auth, runAsUser)) {
              log.error(
                  "User {} does not have access to service account {}",
                  Optional.ofNullable(auth).map(Authentication::getPrincipal).orElse("unknown"),
                  runAsUser);
              return true;
            }
            if (!serviceAccountCanAccessApplication(runAsUser, pipeline.getApplication())) {
              log.error(
                  "Service account {} does not have access to application {}",
                  runAsUser,
                  pipeline.getApplication());
              return true;
            }
            return false;
          });
}