org.apache.shiro.authc.AuthenticationToken Java Examples

The following examples show how to use org.apache.shiro.authc.AuthenticationToken. 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: Realm.java    From permission with Apache License 2.0 6 votes vote down vote up
/**
	 * 认证方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		System.out.println("认证中......");
		UsernamePasswordToken upt = (UsernamePasswordToken)token;
		String pwd = new String(upt.getPassword());
//		// 根据用户名和密码查找用户
		User user = userService.findUserByCodeAndPwd(upt.getUsername(), pwd);
		if(user != null) {
			//返回认证信息
			//参数1:主角,就是登陆的用户
			//参数2:证书,就是凭证,对应密码
			//参数3:当前realm的名称
			return new SimpleAuthenticationInfo(user, pwd, getName());
		}
		return null;
	}
 
Example #2
Source File: DBRealm.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken authenticationToken,
                                                        LdapContextFactory ldapContextFactory) throws NamingException {
    String token = (String) authenticationToken.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);

    if (null==username  || !JwtUtil.verify(token, username)) {
        throw new AuthenticationException("token认证失败!");
    }
    UserModel userModel= userService.getUserByUserName(username);
    if(null==userModel){
        return null;
    }
    return new SimpleAuthenticationInfo(token, token, "MyRealm");
}
 
Example #3
Source File: GitlabAuthenticatingRealm.java    From nexus3-gitlabauth-plugin with MIT License 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (!(token instanceof UsernamePasswordToken)) {
        throw new UnsupportedTokenException(String.format("Token of type %s  is not supported. A %s is required.",
                token.getClass().getName(), UsernamePasswordToken.class.getName()));
    }

    UsernamePasswordToken t = (UsernamePasswordToken) token;
    LOGGER.info("doGetAuthenticationInfo for {}", ((UsernamePasswordToken) token).getUsername());

    GitlabPrincipal authenticatedPrincipal;
    try {
        authenticatedPrincipal = gitlabClient.authz(t.getUsername(), t.getPassword());
        LOGGER.info("Successfully authenticated {}",t.getUsername());
    } catch (GitlabAuthenticationException e) {
        LOGGER.warn("Failed authentication", e);
        return null;
    }

    return createSimpleAuthInfo(authenticatedPrincipal, t);
}
 
Example #4
Source File: CaptchaFormAuthenticationFilter.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
		Subject subject, ServletRequest request, ServletResponse response)
		throws Exception {
	HttpServletRequest httpServletRequest = (HttpServletRequest) request;
	HttpServletResponse httpServletResponse = (HttpServletResponse) response;

	// 登录成功日志
	logLoginStatus(httpServletRequest, LoginType.登录成功);

	if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest
			.getHeader("X-Requested-With"))) {// 不是ajax请求
		issueSuccessRedirect(request, response);
	} else {
		httpServletResponse.setCharacterEncoding("UTF-8");
		PrintWriter out = httpServletResponse.getWriter();
		out.println("{success:true,message:'登录成功'}");
		out.flush();
		out.close();
	}
	return false;
}
 
Example #5
Source File: OAuth2Filter.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setContentType("application/json;charset=utf-8");
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
    httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());

        String json = new Gson().toJson(r);
        httpResponse.getWriter().print(json);
    } catch (IOException e1) {

    }

    return false;
}
 
Example #6
Source File: JwtAuthcFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	if(isJwtSubmission(request)){
		AuthenticationToken token = createJwtToken(request, response);
		try {
			Subject subject = getSubject(request, response);
			subject.login(token);
			return true;
		} catch (AuthenticationException e) {
			LOGGER.error(request.getRemoteHost()+" JWT认证  "+e.getMessage());
			CommonUtils.restFailed(WebUtils.toHttp(response)
					,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage());
		} 
	}
	CommonUtils.restFailed(WebUtils.toHttp(response)
									,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED
									,ShiroProperties.REST_MESSAGE_AUTH_UNAUTHORIZED);
	return false;
}
 
Example #7
Source File: AuthenticationResourceFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest request) {
    Subject subject = new Subject.Builder(_securityManager).buildSubject();
    ThreadContext.bind(subject);

    AuthenticationToken token = _tokenGenerator.createToken(request);
    if (token == null) {
        token = AnonymousToken.getInstance();
    }
    subject.login(token);

    // The user has been successfully logged in.  Update the container authentication.
    setJettyAuthentication(subject);

    return request;
}
 
Example #8
Source File: FormAuthenticationFilter.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * 登录成功调用事件
 */
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

	// 登录成功后初始化授权信息并处理登录后的操作
	authorizingRealm.onLoginSuccess((LoginInfo)subject.getPrincipal(), (HttpServletRequest) request);
	
	// 登录操作如果是Ajax操作,直接返回登录信息字符串。
	if (ServletUtils.isAjaxRequest((HttpServletRequest) request)) {
		request.getRequestDispatcher(getSuccessUrl()).forward(request, response); // AJAX不支持Redirect改用Forward
	}
	// 登录成功直接返回到首页
	else {
		String url = request.getParameter("__url");
		if (StringUtils.isNotBlank(url)) {
			WebUtils.issueRedirect(request, response, url, null, true);
		} else {
			WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
		}
	}
	return false;
}
 
Example #9
Source File: AbstractClientIamAuthenticationFilter.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * determine success redirect URL
 * 
 * @param token
 * @param subject
 * @param request
 * @param response
 * @return
 */
protected String determineSuccessRedirectUrl(AuthenticationToken token, Subject subject, ServletRequest request,
		ServletResponse response) {
	// Priority obtain redirectURL from request.
	String successUrl = getRedirectUrl(request);
	if (isBlank(successUrl)) {
		// Secondary get remembered redirectURL.
		successUrl = getClearSavedRememberUrl(toHttp(request));
		if (isBlank(successUrl)) {
			// Fallback get the configured redirectURL as the default.
			successUrl = config.getSuccessUri();
		}
	}

	// Determine successUrl.
	successUrl = configurer.decorateAuthenticateSuccessUrl(successUrl, token, subject, request, response);
	notNull(successUrl, "'successUrl' must not be null");
	return cleanURI(successUrl); // Check & cleanup.
}
 
Example #10
Source File: ShiroDbRealm.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * 认证回调函数,登录时调用.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    User user = accountService.findUserByLoginName(token.getUsername());
    if (user != null) {
        if (user.getStatus().equals("0")) {//disable
            throw new DisabledAccountException();
        }

        //用户对应的Menu信息
        List<Menu> menus = accountService.findMenuByUserID(user.getId());
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        session.setAttribute("menuList", menus);

        byte[] salt = Encodes.decodeHex(user.getSalt());
        return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName()),
                user.getPassword(), ByteSource.Util.bytes(salt), getName());
    } else {
        return null;
    }
}
 
Example #11
Source File: SessionResource.java    From airpal with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/login")
public void doLogin(
        @Context HttpServletRequest request,
        @Context HttpServletResponse response,
        @FormParam("username") String username,
        @FormParam("password") String password)
        throws IOException
{
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        currentUser.login(token);
    }

    WebUtils.redirectToSavedRequest(request, response, "/app");
}
 
Example #12
Source File: OktaRealm.java    From okta-auth-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    AuthenticationResponse authenticationResponse = ((OktaSuccessLoginToken) token).getAuthenticationResponse();

    // auth already verified, just check the status
    if (authenticationResponse != null
            && authenticationResponse.getStatus() == AuthenticationStatus.SUCCESS
            && authenticationResponse.getSessionToken() != null) {

        // if we have a valid User (see below) return an AuthenticationInfo
        User result = authenticationResponse.getUser();
        if (result != null) {
            SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(result.getLogin(), getName());
            principalCollection.add(result, getName());

            return new SimpleAuthenticationInfo(principalCollection, null);
        }
    }

    return null; // returning null means the user is NOT authenticated
}
 
Example #13
Source File: ShiroKerberosAuthenticationFilterTest.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoginFailure401() {
  subject.login(isA(AuthenticationToken.class));
  expectLastCall().andThrow(new AuthenticationException());

  replayAndStart();

  ClientResponse clientResponse = getRequestBuilder(PATH)
      .header(HttpHeaders.AUTHORIZATION, ShiroKerberosAuthenticationFilter.NEGOTIATE + " asdf")
      .get(ClientResponse.class);

  assertEquals(HttpServletResponse.SC_UNAUTHORIZED, clientResponse.getStatus());
  assertEquals(
      ShiroKerberosAuthenticationFilter.NEGOTIATE,
      clientResponse.getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE));
}
 
Example #14
Source File: HmacRolesFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
	Subject subject = getSubject(request, response); 
	if ((null == subject || !subject.isAuthenticated()) && isHmacSubmission(request)) {
		AuthenticationToken token = createHmacToken(request, response);
		try {
			subject = getSubject(request, response);
			subject.login(token);
			return this.checkRoles(subject,mappedValue);
		} catch (AuthenticationException e) {
			LOGGER.error(request.getRemoteHost()+" HMAC鉴权  "+e.getMessage());
			CommonUtils.restFailed(WebUtils.toHttp(response)
									,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage());
		}	
	}
	return false;
}
 
Example #15
Source File: ApiRealm.java    From flash-waimai with MIT License 6 votes vote down vote up
/**
 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
    String token = (String) auth.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);
    if (username == null) {
        throw new AuthenticationException("token invalid");
    }

    ShiroUser userBean =  ShiroFactroy.me().shiroUser(userService.findByAccount(username));
    if (userBean == null) {
        throw new AuthenticationException("User didn't existed!");
    }

    if (! JwtUtil.verify(token, username, userBean.getPassword())) {
        throw new AuthenticationException("Username or password error");
    }

    return new SimpleAuthenticationInfo(token, token, "my_realm");
}
 
Example #16
Source File: MyShiroRealm.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
    throws AuthenticationException {
    final String account = (String)token.getPrincipal();
    final User user = this.membershipFacade.getUser(account);

    if (user == null) {
        throw new UnknownAccountException();
    }
    if (user.getStatus() == 0) {
        throw new LockedAccountException();
    }

    // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
    return new SimpleAuthenticationInfo(
        user.getAccount(), user.getPassword(),
        ByteSource.Util.bytes(user.getCredentialsSalt()),
        getName());
}
 
Example #17
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 用户认证
 *
 * @param authenticationToken 身份认证 token
 * @return AuthenticationInfo 身份认证信息
 * @throws AuthenticationException 认证相关异常
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的,已经经过了解密
    String token = (String) authenticationToken.getCredentials();

    String username = JWTUtil.getUsername(token);

    if (StringUtils.isBlank(username))
        throw new AuthenticationException("token校验不通过");

    // 通过用户名查询用户信息
    User user = SystemUtils.getUser(username);

    if (user == null)
        throw new AuthenticationException("用户名或密码错误");
    if (!JWTUtil.verify(token, username, user.getPassword()))
        throw new AuthenticationException("token校验不通过");
    return new SimpleAuthenticationInfo(token, token, "shiro_realm");
}
 
Example #18
Source File: OAuth2Filter.java    From renren-fast with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setContentType("application/json;charset=utf-8");
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        R r = R.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());

        String json = new Gson().toJson(r);
        httpResponse.getWriter().print(json);
    } catch (IOException e1) {

    }

    return false;
}
 
Example #19
Source File: SearchFirstActiveDirectoryRealm.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Nullable
private AuthenticationInfo queryForAuthenticationInfo0(
        AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

    final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token);
    final String userDn = findUserDn(ldapContextFactory, upToken.getUsername());
    if (userDn == null) {
        return null;
    }

    LdapContext ctx = null;
    try {
        // Binds using the username and password provided by the user.
        ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword());
    } catch (AuthenticationException e) {
        // According to this page, LDAP error code 49 (invalid credentials) is the only case where
        // AuthenticationException is raised:
        // - https://docs.oracle.com/javase/tutorial/jndi/ldap/exceptions.html
        // - com.sun.jndi.ldap.LdapCtx.mapErrorCode()
        return null;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
 
Example #20
Source File: NexusBasicHttpAuthenticationFilter.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
                                 Subject subject,
                                 ServletRequest request,
                                 ServletResponse response)
    throws Exception
{
  if (request instanceof HttpServletRequest) {
    // Prefer the subject principal over the token's, as these could be different for token-based auth
    Object principal = subject.getPrincipal();
    if (principal == null) {
      principal = token.getPrincipal();
    }
    String userId = principal.toString();

    // Attach principal+userId to request so we can use that in the request-log
    request.setAttribute(ATTR_USER_PRINCIPAL, principal);
    request.setAttribute(ATTR_USER_ID, userId);
  }
  return super.onLoginSuccess(token, subject, request, response);
}
 
Example #21
Source File: HttpHeaderAuthenticationTokenFactorySupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Nullable
public AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
  List<String> headerNames = getHttpHeaderNames();
  if (headerNames != null) {
    HttpServletRequest httpRequest = WebUtils.toHttp(request);
    for (String headerName : headerNames) {
      String headerValue = httpRequest.getHeader(headerName);
      if (headerValue != null) {
        return createToken(headerName, headerValue, request.getRemoteHost());
      }
    }
  }
  return null;
}
 
Example #22
Source File: AjaxAuthenticationFilter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
	if (WebHelper.isAjax((HttpServletRequest) request)) {
		writeObject(request, response, Result.success());
		return false;
	}
	return super.onLoginSuccess(token, subject, request, response);
}
 
Example #23
Source File: ShiroConfiguration.java    From roncoo-jui-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
	UsernamePasswordToken token = (UsernamePasswordToken) arg0;
	// String roncooNo = token.getUsername();
	// String password = token.getPassword().toString();
	
	SecurityUtils.getSubject().getSession().setAttribute(Constants.Session.USER, sysUserDao.getByUserPhone(ConfUtil.USER));
	return new SimpleAuthenticationInfo(token, token.getPassword(), getName());
}
 
Example #24
Source File: ShiroClient.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void login(Object credentials) throws AuthenticationException {
   if(!(credentials instanceof AuthenticationToken)) {
      throw new UnsupportedTokenException("Invalid authentication token");
   }
   
   subject.login((AuthenticationToken) credentials);
}
 
Example #25
Source File: ShiroService.java    From VideoMeeting with Apache License 2.0 5 votes vote down vote up
/**
 * 验证当前登录的subject
 */
@Transactional
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
		AuthenticationToken token) throws AuthenticationException {
	System.out.println("--------------doGetAuthenticationInfo------------");
	String username = (String) token.getPrincipal();
	System.out
			.println("--------------doGetAuthenticationInfo------------username:"
					+ username);
	// User user = userService.getByUserName(username);
	// FIXME null exception by userDAO
	User user = userDao.get("from User u where u.username = ?",
			new String[] { username });
	if (user == null) {
		throw new UnknownAccountException(); // 没找到帐号
	}

	// if(Boolean.TRUE.equals(user.getLocked())) {
	// throw new LockedAccountException(); //帐号锁定
	// }
	// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得不好可以在此判断或自定义实现
	// 通过在配置文件汇总进行如下配置进行密码匹配
	SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
			user.getUsername(), // 用户名
			user.getPassword(), // 密码
			// ByteSource.Util.bytes(user.getCredentialsSalt()),//
			// salt=username+salt
			new MySimpleByteSource(user.getCredentialsSalt()), getName() // realm
																			// name
	);
	return authenticationInfo;
}
 
Example #26
Source File: AuthzPrincipalRepositoryImpl.java    From spring-boot-starter-samples with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	
	UsernamePasswordToken upToken = (UsernamePasswordToken) token;
	
	if( !StringUtils.hasText(upToken.getUsername()) || upToken.getPassword() == null ){
		throw new UnknownAccountException("Username or password is required.");
	}
	//密码加密
	String pwd = new String(upToken.getPassword());//Base64.encodeBase64String(new String(upToken.getPassword()).getBytes());
	//账号状态
	Map<String, String> statusMap = getAuthzLoginDao().getAccountStatus(upToken.getUsername(), pwd);
  		//账号不存在 或 用户名或密码不正确
  		if("0".equals(statusMap.get("num_1")) || "0".equals(statusMap.get("num_2"))){
  			throw new InvalidAccountException("Username or password is incorrect, please re-enter.");
  		}
  		// 账号被禁用
	else if ("0".equals(statusMap.get("num_4"))) {
		throw new DisabledAccountException("Account is disabled.");
	}
  		//用户无所属角色
  		else if("0".equals(statusMap.get("num_3"))){
           throw new NoneRoleException();
  		}
  		
  		// 用户主体对象
  		AuthzLoginModel model = getAuthzLoginDao().getAccount(upToken.getUsername(), pwd);
  		// 用户角色ID集合
  		List<String> roles = getAuthzUserDao().getRoles(model.getUserid());
  		model.setRoles(Sets.newHashSet(roles.iterator()));
  		model.setRoleid(roles.get(0));
  		// 用户权限标记集合
  		Set<String> perms =  Sets.newHashSet();
	for (String roleid : model.getRoles()) {
		perms.addAll(getAuthzRolePermsDao().getPermissions(roleid));
	}
	model.setPerms(perms);
  		// 认证信息
	return new SimpleAuthenticationInfo(model, upToken.getPassword(), "login");
}
 
Example #27
Source File: FormAuthenticationFilter.java    From easyweb with Apache License 2.0 5 votes vote down vote up
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
	String username = getUsername(request);
	String password = getPassword(request);
	if (password==null){
		password = "";
	}
	boolean rememberMe = isRememberMe(request);
	String host = StringUtils.getRemoteAddr((HttpServletRequest)request);
	String captcha = getCaptcha(request);
	boolean mobile = isMobileLogin(request);
	return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha);
}
 
Example #28
Source File: WebSession.java    From onedev with MIT License 5 votes vote down vote up
public void login(AuthenticationToken token) {
	Subject subject = SecurityUtils.getSubject();

	// Force a new session to prevent session fixation attack.
	// We have to invalidate via both Shiro and Wicket; otherwise it doesn't
	// work.
	subject.getSession().stop();
	replaceSession(); 

	subject.login(token);
}
 
Example #29
Source File: GreenStepMobileFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, 
		ServletRequest request, ServletResponse response) throws Exception {
	
       HttpServletRequest httpServletRequest = (HttpServletRequest)request;
       HttpServletResponse httpServletResponse = (HttpServletResponse)response;
       if (!this.isAjaxRequest(httpServletRequest)) {
       	httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
       } else {
   		response.setCharacterEncoding( Constants.BASE_ENCODING );
   		response.setContentType("application/json");
   		response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA);
       }
	return false;
}
 
Example #30
Source File: ShiroKerberosAuthenticationFilterTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoginSuccess200() throws ServletException, IOException {
  subject.login(isA(AuthenticationToken.class));
  mockServlet.service(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class));

  replayAndStart();

  ClientResponse clientResponse = getRequestBuilder(PATH)
      .header(HttpHeaders.AUTHORIZATION, ShiroKerberosAuthenticationFilter.NEGOTIATE + " asdf")
      .get(ClientResponse.class);

  assertEquals(HttpServletResponse.SC_OK, clientResponse.getStatus());
}