List of usage examples for org.apache.shiro.subject Subject login
void login(AuthenticationToken token) throws AuthenticationException;
From source file:io.bootique.shiro.ShiroModuleIT.java
License:Apache License
@Test public void testFullStack_AuthListenerType() { TestAuthListener.reset();// ww w . j av a 2 s. c om Realm mockRealm = mockRealm(); BQRuntime runtime = testFactory.app() .module(b -> ShiroModule.extend(b).addRealm(mockRealm).addAuthListener(TestAuthListener.class)) .autoLoadModules().createRuntime(); Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject(); assertFalse(subject.isAuthenticated()); // try bad login try { subject.login(new UsernamePasswordToken("uname", "badpassword")); Assert.fail("Should have thrown on bad auth"); } catch (AuthenticationException authEx) { assertTrue(TestAuthListener.onFailure); } // try good login subject.login(new UsernamePasswordToken("uname", "password")); assertTrue(TestAuthListener.onSuccess); }
From source file:io.buji.pac4j.ClientFilter.java
License:Apache License
/** * Execute login by creating {@link #createToken(javax.servlet.ServletRequest, javax.servlet.ServletResponse) token} and logging subject * with this token./*from www . j a v a2s. co m*/ * * @param request the incoming request * @param response the outgoing response * @throws Exception if there is an error processing the request. */ @Override protected boolean onAccessDenied(final ServletRequest request, final ServletResponse response) throws Exception { final AuthenticationToken token; try { token = createToken(request, response); } catch (final RequiresHttpAction e) { log.debug("requires HTTP action : {}", e); return false; } try { final Subject subject = getSubject(request, response); subject.login(token); return onLoginSuccess(token, subject, request, response); } catch (final NoAuthenticationException e) { // no authentication happens but go to the success url however : // the protecting filter will have the appropriate behaviour return onLoginSuccess(token, null, request, response); } catch (final AuthenticationException e) { return onLoginFailure(token, e, request, response); } }
From source file:io.cassandrareaper.resources.auth.LoginResource.java
License:Apache License
@Path("/login") @POST/*from w w w. j ava 2 s. c o m*/ public void login(@FormParam("username") String username, @FormParam("password") String password, @Auth Subject subject) throws IOException { ensurePresent(username, "Invalid credentials: missing username."); ensurePresent(password, "Invalid credentials: missing password."); try { subject.login(new UsernamePasswordToken(username, password)); } catch (AuthenticationException e) { throw new IncorrectCredentialsException("Invalid credentials combination for user: " + username); } }
From source file:io.github.howiefh.console.ShiroDemo.java
public static void main(String[] args) { log.info("My First Apache Shiro Application"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // ??://from w ww . j ava2 s .c o m Subject currentUser = SecurityUtils.getSubject(); // ? Session Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // ??? if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... ? catch (AuthenticationException ae) { // ?? } } // ?: // ??? ( username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); // : if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } // ?? (? instance-level ) if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } // (?)??: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } // ? - t! currentUser.logout(); System.exit(0); }
From source file:io.github.howiefh.jeews.modules.oauth2.controller.AuthorizeController.java
License:Apache License
private boolean login(Subject subject, HttpServletRequest request) { if ("get".equalsIgnoreCase(request.getMethod())) { return false; }//from w ww.j av a2s .c om String username = request.getParameter("username"); String password = request.getParameter("password"); if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { return false; } UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { subject.login(token); return true; } catch (Exception e) { throw new RuntimeException("login error: " + e.getMessage()); } }
From source file:io.hops.hopsworks.api.zeppelin.rest.LoginRestApi.java
License:Apache License
/** * Post Login//from ww w.j a va2 s . c o m * Returns userName & password * for anonymous access, username is always anonymous. * After getting this ticket, access through websockets become safe * * @param userName * @param password * @return 200 response */ @POST public Response postLogin(@FormParam("userName") String userName, @FormParam("password") String password) { JsonResponse response = null; // ticket set to anonymous for anonymous user. Simplify testing. Subject currentUser = org.apache.shiro.SecurityUtils.getSubject(); if (currentUser.isAuthenticated()) { currentUser.logout(); } if (!currentUser.isAuthenticated()) { try { UsernamePasswordToken token = new UsernamePasswordToken(userName, password); // token.setRememberMe(true); currentUser.login(token); HashSet<String> roles = SecurityUtils.getRoles(); String principal = SecurityUtils.getPrincipal(); String ticket; if ("anonymous".equals(principal)) { ticket = "anonymous"; } else { ticket = TicketContainer.instance.getTicket(principal); } Map<String, String> data = new HashMap<>(); data.put("principal", principal); data.put("roles", roles.toString()); data.put("ticket", ticket); response = new JsonResponse(Response.Status.OK, "", data); //if no exception, that's it, we're done! //set roles for user in NotebookAuthorization module NotebookAuthorization.getInstance().setRoles(principal, roles); } catch (UnknownAccountException uae) { //username wasn't in the system, show them an error message? LOG.error("Exception in login: ", uae); } catch (IncorrectCredentialsException ice) { //password didn't match, try again? LOG.error("Exception in login: ", ice); } catch (LockedAccountException lae) { //account for that username is locked - can't login. Show them a message? LOG.error("Exception in login: ", lae); } catch (AuthenticationException ae) { //unexpected condition - error? LOG.error("Exception in login: ", ae); } } if (response == null) { response = new JsonResponse(Response.Status.FORBIDDEN, "", ""); } LOG.warn(response.toString()); return response.build(); }
From source file:io.starter.TestContent.java
License:Open Source License
/** * test cpntent ownership ratings// w ww.ja v a 2 s . co m * * @throws Exception */ @Test public void testOwnershipPermissions() throws Exception { Content content = new Content(); content.setAuthor(42); content.setUserId(42); content.setAuthorDevice(1); content.setCopyright("Copyright 2014. All rights reserved"); content.setDescription("TEST Starter Content"); content.setLicense("CC"); content.setFlag(FLAG_STAR); content.setMimeType("text/html"); content.setUrl("http://$$PROJECT_DOMAIN$$"); content.setPostDate(new java.util.Date(System.currentTimeMillis())); sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(true); session.insert("io.starter.dao.ContentMapper.insert", content); session.commit(); Integer id = content.getId(); assertTrue(id != null); Content ccx = session.selectOne("io.starter.dao.ContentMapper.selectObjByPrimaryKey", id); User user = ccx.getUser(); assertTrue(ccx.getUserId() == 42); // assert that contact info is stripped from this assertEquals(null, user.getEmail()); // and that we got the right user assertEquals("test", user.getUsername()); // 1. Build the Subject instance for the test to run: Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject(); // 2. Bind the subject to the current thread: setSubject(subjectUnderTest); // see /login.jsp for these form fields String username = "test"; String password = API_CRYPT_KEY; // create a UsernamePasswordToken using the // username and password provided by the user UsernamePasswordToken token = new UsernamePasswordToken(username, password); // get the user (aka subject) associated with this request. Subject subject = SecurityUtils.getSubject(); try { subject.checkPermission("thing:action"); fail("User INCORRECTLY has permission thing:action"); } catch (AuthorizationException x) { // GOOD! } subject.login(token); user.setSubject(subject); ContentData.setContentOwnerPermissions(content, user, session); WildcardPermission owner = new WildcardPermission(SystemConstants.SECURITY_TARGET_TYPE_CONTENT + ":" + SystemConstants.SECURITY_ACL_OWNER + ":" + content.getId()); assert (user.checkAccess(owner)); // test deletion of that new content session = sqlSessionFactory.openSession(true); session.delete("io.starter.dao.ContentMapper.deleteByPrimaryKey", ccx); try { Content ccd = session.selectOne("io.starter.dao.ContentMapper.selectByPrimaryKey", id); String s1 = ccd.getDescription(); if (s1 != null) fail("Failed to delete inserted Content ID: " + id); } catch (Exception x) { // good! } session.close(); }
From source file:io.vertx.ext.auth.impl.realms.ShiroAuthRealmImpl.java
License:Open Source License
@Override public String login(JsonObject credentials) { SubjectContext subjectContext = new DefaultSubjectContext(); Subject subject = securityManager.createSubject(subjectContext); String username = credentials.getString("username"); String password = credentials.getString("password"); AuthenticationToken token = new UsernamePasswordToken(username, password); try {/*from ww w. ja v a 2 s.com*/ subject.login(token); return subject.getPrincipal().toString(); } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException | ExcessiveAttemptsException e) { return null; } catch (AuthenticationException ae) { // Unexpected exception - log it log.error("Unexpected exception when logging in", ae.getCause()); return null; } }
From source file:io.vertx.ext.auth.shiro.impl.ShiroAuthProviderImpl.java
License:Open Source License
@Override public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) { vertx.executeBlocking(fut -> {/*from w ww.j a v a 2s .c o m*/ SubjectContext subjectContext = new DefaultSubjectContext(); Subject subject = securityManager.createSubject(subjectContext); String username = authInfo.getString("username"); String password = authInfo.getString("password"); AuthenticationToken token = new UsernamePasswordToken(username, password); try { subject.login(token); } catch (AuthenticationException e) { throw new VertxException(e); } fut.complete(new ShiroUser(vertx, securityManager, subject, rolePrefix)); }, resultHandler); }
From source file:io.vertx.ext.auth.shiro.impl.ShiroAuthRealmBase.java
License:Open Source License
@Override public void login(JsonObject principal, JsonObject credentials) { SubjectContext subjectContext = new DefaultSubjectContext(); Subject subject = securityManager.createSubject(subjectContext); String username = principal.getString("username"); String password = credentials.getString("password"); AuthenticationToken token = new UsernamePasswordToken(username, password); try {/*from w w w.j av a 2s. c o m*/ subject.login(token); } catch (AuthenticationException e) { throw new VertxException(e); } }