本文整理匯總了Java中org.apache.shiro.authc.AuthenticationException類的典型用法代碼示例。如果您正苦於以下問題:Java AuthenticationException類的具體用法?Java AuthenticationException怎麽用?Java AuthenticationException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
AuthenticationException類屬於org.apache.shiro.authc包,在下文中一共展示了AuthenticationException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: onLoginFailure
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
ServletResponse response) {
final OAuthResponse oAuthResponse;
try {
oAuthResponse = OAuthRSResponse.errorResponse(401)
.setError(OAuthError.ResourceResponse.INVALID_TOKEN)
.setErrorDescription(ae.getMessage())
.buildJSONMessage();
com.monkeyk.os.web.WebUtils.writeOAuthJsonResponse((HttpServletResponse) response, oAuthResponse);
} catch (OAuthSystemException e) {
LOGGER.error("Build JSON message error", e);
throw new IllegalStateException(e);
}
return false;
}
示例2: doGetAuthenticationInfo
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
/**
* 認證回調函數,登錄時調用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePassword2Token token = (UsernamePassword2Token) authcToken;
String username = token.getUsername();
if (username == null || null == username) {
throw new AccountException(
"Null usernames are not allowed by this realm.");
}
User entity = new User();
entity.setEmail(username);
entity.setStatus(Constant.STATUS_ENABLED);
entity = (User) service.iUserService.select(entity);
if (null == entity) {
throw new UnknownAccountException("No account found for user ["
+ username + "]");
}
byte[] key = Encode.decodeHex(entity.getRandom());
return new SimpleAuthenticationInfo(new Shiro(entity.getId(),
entity.getEmail(), entity.getName()), entity.getPassword(),
ByteSource.Util.bytes(key), getName());
}
示例3: doGetAuthenticationInfo
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//UsernamePasswordToken對象用來存放提交的登錄信息
UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
log.info("驗證當前Subject時獲取到token為:" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
// return new SimpleAuthenticationInfo("hsjhsj","8e24137dee97c9bbddb9a0cd6e043be4" , getName());
return new SimpleAuthenticationInfo("hsjhsj","" , getName());
//查出是否有此用戶
// TbUser user=null;
// if(user!=null){
// 若存在,將此用戶存放到登錄認證info中,無需自己做密碼對比,Shiro會為我們進行密碼對比校驗
// return new SimpleAuthenticationInfo(user.getUsername(), , getName());
// }
// return null;
}
示例4: doGetAuthenticationInfo
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
String token = (String) auth.getCredentials();
Cache<String, String> authCache = CacheController.getAuthCache();
if (! authCache.containsKey(token)) {
// get user info from database
int uid = JWTUtil.getUid(token);
UserEntity userEntity = userService.getUserByUid(uid);
authCache.put(token, String.valueOf(userEntity.getPassword()));
}
String secret = authCache.get(token);
if (!JWTUtil.decode(token, secret)) {
throw new AuthenticationException("Token invalid");
}
return new SimpleAuthenticationInfo(token, token, "jwt_realm");
}
示例5: login
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
/**
* 用戶登錄
* @param request
* @param user
* @param model
* @return
*/
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(HttpServletRequest request, AdminUser user, Model model) {
if (StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
request.setAttribute("msg","用戶名或者密碼不能為空!");
return "login";
}
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
try {
subject.login(token);
return "redirect:/initPage";
}catch (LockedAccountException lae) {
token.clear();
request.setAttribute("msg", "用戶已經被鎖定不能登錄,請與管理員聯係!");
return "login";
} catch (AuthenticationException e) {
token.clear();
request.setAttribute("msg", "用戶或密碼不正確!");
return "login";
}
}
示例6: onLoginFailure
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@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;
}
示例7: doGetAuthenticationInfo
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
/**
* 用戶認證-驗證用戶是否登錄、用戶名密碼是否匹配
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
logger.info(">>> 【用戶認證】token = {}", token);
String userName = (String)token.getPrincipal();
AdminUser user = getPrincipalService().getPrincipalObject(userName);
if(user == null) {
throw new UnknownAccountException("Unknown account: " + userName);//沒找到帳號
}
if(AdminUserStatusEnum.ADMIN_USER_STATUS_DISABLED.getStatusCode().equals(user.getStatus())) {
throw new LockedAccountException("Account[" + userName + "] has been locked!"); //帳號鎖定
}
//交給AuthenticatingRealm使用CredentialsMatcher進行密碼匹配
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user.getUserName(), //用戶名
user.getPassword(), //密碼
ByteSource.Util.bytes(user.getPasswordSalt()),//salt
getName() //realm name
);
return authenticationInfo;
}
示例8: onLoginFailure
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
if (!((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")) {
setFailureAttribute(request, e);
return true;
}
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
String message = e.getClass().getSimpleName();
if ("IncorrectCredentialsException".equals(message)
|| "UnknownAccountException".equals(message)
) {
out.println("{\"code\":-100010,\"info\":\"賬號或密碼錯誤\"}");
}else if("ExcessiveAttemptsException".equals(message)){
out.println("{\"code\":-100020,\"info\":\"密碼錯誤次數超過限製,請10分鍾後重試!\"}");
}else if("LockedAccountException".equals(message)){
out.println("{\"code\":-100030,\"info\":\"賬號已停用!\"}");
} else {
out.println("{\"code\":-100500,\"info\":\"未知錯誤\"}");
}
out.flush();
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
示例9: testHelloWorld
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Test
public void testHelloWorld() {
//1、獲取 SecurityManager 工廠,此處使用 Ini 配置文件初始化 SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2、得到 SecurityManager 實例 並綁定給 SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到 Subject 及創建用戶名/密碼身份驗證 Token(即用戶身份/憑證)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("test", "234");
try {
//4、登錄,即身份驗證
subject.login(token);
} catch (AuthenticationException e) {
//5、身份驗證失敗
}
Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登錄
//6、退出
subject.logout();
}
示例10: isAccessAllowed
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String token = jwtHelper.getToken(request);
String username = jwtHelper.getUsernameFromToken(token);
StatelessToken accessToken = new StatelessToken(username, token);
try {
getSubject(servletRequest, servletResponse).login(accessToken);
} catch (AuthenticationException e) {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
objectMapper.writeValue(response.getWriter(), Result.fail(ResultCode.UNAUTHORIZED));
return false;
}
getSubject(servletRequest, servletResponse).isPermitted(request.getRequestURI());
return true;
}
示例11: onLoginFailure
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
ServletResponse response) {
// OAuth2Token oAuth2Token = (OAuth2Token) token;
final OAuthResponse oAuthResponse;
try {
oAuthResponse = OAuthRSResponse.errorResponse(401)
.setError(OAuthError.ResourceResponse.INVALID_TOKEN)
.setErrorDescription(ae.getMessage())
.buildJSONMessage();
com.monkeyk.os.web.WebUtils.writeOAuthJsonResponse((HttpServletResponse) response, oAuthResponse);
} catch (OAuthSystemException e) {
logger.error("Build JSON message error", e);
throw new IllegalStateException(e);
}
return false;
}
示例12: doGetAuthenticationInfo
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// identify account to log to
UsernamePasswordToken userPassToken = (UsernamePasswordToken) token;
final String username = userPassToken.getUsername();
if (username == null) {
return null;
}
// read password hash and salt from db
final User user = UserDAO.getUser(username);
if (user == null) {
return null;
}
// return salted credentials
SaltedAuthenticationInfo info = new SaltedAuthInfo(username, user.getPassword(), user.getSalt());
return info;
}
示例13: login
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@PostMapping(value = SUBPATH_LOGIN)
public ResponseEntity<UserDto> login(@RequestBody UserDto userDto,
UriComponentsBuilder uriComponentsBuilder){
HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,SUBPATH_LOGIN);
logger.info("================userInfo================username: " + userDto.getUsername() + ",pw: " + userDto.getPassword());
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userDto.getUsername(),userDto.getPassword());
//User user = new User("root","root","root","root");
//userDao.save(user);
try{
subject.login(token);
} catch (AuthenticationException e){
logger.error("======登錄失敗======");
throw new ResultException(ErrorCode.USERNAMEORPASSWORD.getDesc(),ErrorCode.USERNAMEORPASSWORD);
}
UserDto loginUserDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("user");
return new ResponseEntity<>(loginUserDto,headers, HttpStatus.OK);
}
示例14: login
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView login(User user, String captcha, HttpSession session,HttpServletRequest request) throws Exception{
ModelAndView mv = new ModelAndView();
String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
System.out.println(kaptchaExpected);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
try{
subject.login(token);
mv.setViewName("redirect:/index.jsp");
} catch (AuthenticationException e){
mv.addObject("message", "login errors");
mv.setViewName("redirect:/backend/login");
}
return mv;
}
示例15: hello
import org.apache.shiro.authc.AuthenticationException; //導入依賴的package包/類
@RequestMapping(value ="/hello")
@ResponseBody
public String hello(){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhansan", "123456");
//--4. 登錄,即身份驗證
try {
subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
}
//System.out.println(subject.isAuthenticated());
//System.out.println(subject.getPrincipal());
//-- 6. 退出
System.out.println(subject.isAuthenticated());
subject.logout();
return "hello";
}