public static void main(String args[]) throws java.lang.Exception { URL wsdlURL = AuthenticationBeanService.WSDL_LOCATION; if (args.length > 0 && args[0] != null && !"".equals(args[0])) { File wsdlFile = new File(args[0]); try { if (wsdlFile.exists()) { wsdlURL = wsdlFile.toURI().toURL(); } else { wsdlURL = new URL(args[0]); } } catch (MalformedURLException e) { e.printStackTrace(); } } AuthenticationBeanService ss = new AuthenticationBeanService(wsdlURL, SERVICE_NAME); Authentication port = ss.getAuthenticationPort(); { System.out.println("Invoking login..."); java.lang.String _login_arg0 = ""; java.lang.String _login_arg1 = ""; java.lang.String _login__return = port.login(_login_arg0, _login_arg1); System.out.println("login.result=" + _login__return); } { System.out.println("Invoking ping..."); java.lang.String _ping__return = port.ping(); System.out.println("ping.result=" + _ping__return); } System.exit(0); }
@Override public Payload apply(String uri, Context context, PayloadSupplier nextFilter) throws Exception { if (authentication.isAuthenticated(context)) { User user = authentication.getUser(context); context.setCurrentUser(user); } return nextFilter.get(); }
/** * @param principal Principal used to retrieve the <code>Authentication</code> object. * @param credentials Credentials used for the authentication. * @return <code>true</code> if Credentials authenticate, <code>false</code> if no <code> * Authentication</code> can handle the given <code>Credentials</code> * @throws javax.security.auth.login.FailedLoginException if the authentication failed. * @throws RepositoryException If another error occurs. * @see AbstractLoginModule#getAuthentication(java.security.Principal, javax.jcr.Credentials) * @see AbstractLoginModule#authenticate(java.security.Principal, javax.jcr.Credentials) */ protected boolean authenticate(Principal principal, Credentials credentials) throws FailedLoginException, RepositoryException { Authentication auth = getAuthentication(principal, credentials); if (auth == null) { return false; } else if (auth.authenticate(credentials)) { return true; } throw new FailedLoginException(); }
/** * POST api/authentication?token=xxx * * <p>This action is called after signing the nonce on the client-side with the user's * certificate. We'll once again use the Authentication class to do the actual work. */ @RequestMapping( value = "/api/authentication", method = {RequestMethod.POST}) public AuthenticationPostResponse post( @RequestParam(value = "token", required = true) String token) throws RestException { // Instantiate the Authentication class Authentication auth = new Authentication(Util.getRestPkiClient()); // Call the completeWithWebPki() method, which finalizes the authentication process. It receives // as input // only the token that was yielded previously (which we sent to the page and the page sent us // back on the URL). // The call yields a ValidationResults which denotes whether the authentication was successful // or not. ValidationResults vr = auth.completeWithWebPki(token); AuthenticationPostResponse response = new AuthenticationPostResponse(); // Check the authentication result if (!vr.isValid()) { // If the authentication failed, inform the page response.setSuccess(false); response.setMessage("Authentication failed"); response.setValidationResults(vr.toString()); return response; } // At this point, you have assurance that the certificate is valid according to the // SecurityContext passed on the first step (see method get()) and that the user is indeed the // certificate's // subject. Now, you'd typically query your database for a user that matches one of the // certificate's fields, such as cert.getEmailAddress() or cert.getPkiBrazil().getCpf() (the // actual field // to be used as key depends on your application's business logic) and set the user // as authenticated with whatever web security framework your application uses. // For demonstration purposes, we'll just return a success and put on the message something // to show that we have access to the certificate's fields. PKCertificate userCert = auth.getPKCertificate(); StringBuilder message = new StringBuilder(); message.append("Welcome, " + userCert.getSubjectName().getCommonName() + "!"); if (!StringUtils.isEmpty(userCert.getEmailAddress())) { message.append(" Your email address is " + userCert.getEmailAddress()); } if (!StringUtils.isEmpty(userCert.getPkiBrazil().getCpf())) { message.append(" and your CPF is " + userCert.getPkiBrazil().getCpf()); } // Return success to the page response.setSuccess(true); response.setMessage(message.toString()); return response; }
/** * Returns the Authentication for the current user. * * @param context The current Android context. * @return The Authentication object containing the accound and the Singly access token. */ public Authentication getAuthentication(Context context) { SharedPreferences prefs = context.getSharedPreferences("singly", Context.MODE_PRIVATE); String account = prefs.getString(ACCOUNT, null); String accessToken = prefs.getString(ACCESS_TOKEN, null); Authentication auth = new Authentication(); auth.account = account; auth.accessToken = accessToken; return auth; }
public void newUser(String name, Privileges privileges) throws IOException, IllegalUsernameException { try { assertValidName(name); users.save(new User.Builder().withName(name).withPrivileges(privileges).build()); // All users, by default, have their name as their password, usable only in order to set the // password in a // subsequent request. authentication.setPassword(name, name); authentication.requirePasswordChange(name); } catch (IllegalTokenException e) { throw new ThisShouldNotHappenError("Jake", "There is no token set at this point.", e); } }
/** * 过滤逻辑:首先判断单点登录的账户是否已经存在本系统中, 如果不存在使用用户查询接口查询出用户对象并设置在Session中 * * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest httpRequest = (HttpServletRequest) request; // _const_cas_assertion_是CAS中存放登录用户名的session标志 Object object = httpRequest.getSession().getAttribute("_const_cas_assertion_"); if (object != null) { Assertion assertion = (Assertion) object; String loginName = assertion.getPrincipal().getName(); // 第一次登录系统 if (httpRequest.getSession().getAttribute("userid") == null) { System.out.println(loginName + "第一次登录"); UserOBJ visitor = Authentication.checkUser(loginName); HttpSession session = httpRequest.getSession(); session.setAttribute("userid", loginName); // 用户ID session.setAttribute("username", visitor.username); // 姓名 session.setAttribute("groupid", visitor.groupid); // 机构ID session.setAttribute("groupname", visitor.groupname); // 机构名称 session.setAttribute("pid", visitor.pid); // 上级机构ID session.setAttribute("pname", visitor.pname); // 上级机构名称 session.setAttribute("jgcode", visitor.jgcode); // 营销机构代码 session.setAttribute("station", visitor.station); // 银保机构代码 session.setAttribute("mobile", visitor.mobile); // 手机号码 session.setAttribute("phone", visitor.phone); // 座机电话 } } // pass the request along the filter chain chain.doFilter(request, response); }
/** * This method queries Google Reader for the list of subscribed feeds. * * @param sid authentication code to pass along in a cookie. * @return arr returns a JSONArray of JSONObjects for each feed. * <p>The JSONObject returned by the service looks like this: id: this is the feed url. title: * this is the title of the feed. sortid: this has not been figured out yet. firstitemsec: * this has not been figured out yet. */ public static JSONArray getSubscriptionList(String sid) { final DefaultHttpClient client = new DefaultHttpClient(); final HttpGet get = new HttpGet(SUB_URL + "/list?output=json"); final BasicClientCookie cookie = Authentication.buildCookie(sid); try { client.getCookieStore().addCookie(cookie); final HttpResponse response = client.execute(get); final HttpEntity respEntity = response.getEntity(); Log.d(TAG, "Response from server: " + response.getStatusLine()); final InputStream in = respEntity.getContent(); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; String arr = ""; while ((line = reader.readLine()) != null) { arr += line; } final JSONObject obj = new JSONObject(arr); final JSONArray array = obj.getJSONArray("subscriptions"); reader.close(); client.getConnectionManager().shutdown(); return array; } catch (final Exception e) { Log.d(TAG, "Exception caught:: " + e.toString()); return null; } }
@RequestMapping(value = "/user", method = RequestMethod.PUT) @Transactional public ResponseEntity<Client> doIt(@RequestBody Client client, Authentication authentication) { List<String> errors = DomainValidator.checkForErrors(client); if (!errors.isEmpty()) { return new ResponseEntity<Client>(new Client(client, errors), HttpStatus.BAD_REQUEST); } HttpStatus status = null; List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("USER")); if (ApplicationSecurity.isRoot(authentication)) { if (ApplicationSecurity.isRoot(client.getUsername())) { return new ResponseEntity<Client>( new Client(client, cannotChangeRootPassword), HttpStatus.BAD_REQUEST); } status = upsert(client, authorities); } else if (StringUtils.equals(client.getUsername(), authentication.getName())) { if (!userDetailsManager.userExists(client.getUsername())) { return new ResponseEntity<Client>(new Client(client, mustBeRoot), HttpStatus.BAD_REQUEST); } User user = new User(client.getUsername(), client.getPassword(), authorities); userDetailsManager.updateUser(user); status = HttpStatus.OK; } else { return new ResponseEntity<Client>(HttpStatus.FORBIDDEN); } return new ResponseEntity<Client>(new Client(client), status); }
/** * This method returns true or false, which depend on the response PDU. If the response PDU is not * null and don't have an error, true will be returned. * * @param responsePDU the responsePDU, which will be checked for errors. * @return - true if no error was invoked else false. * @throws PDURequestFailedException - If an error occurred in the response PDU. * @throws SNMPTimeOutException - If a timeout occured * @see org.snmp4j.PDU */ public boolean checkResponsePDU(PDU responsePDU) throws PDURequestFailedException, SNMPTimeOutException { if (responsePDU != null) if (responsePDU.getErrorStatus() == PDU.noError) return true; else throw new PDURequestFailedException(responsePDU); else throw new SNMPTimeOutException("Timeout: No Response from " + authentication.getAddress()); }
static { try { session = NotesFactory.createSession((String) null, (String) null, Authentication.getInfo()); thisDb = session.getCurrentDatabase(); } catch (NotesException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void updateState() { switch (authentication.getState()) { case Authentication.AUTHORIZED: button.setText(getString(R.string.button_logout)); button.setOnClickListener(logoutAction); textView.setText( getString(R.string.text_logged_in, authentication.getOAuth().getUser().getUsername())); break; case Authentication.REQUESTING_AUTHORIZATION: button.setText(getString(R.string.button_cancel_authentication)); button.setOnClickListener(logoutAction); textView.setText(getString(R.string.text_waiting_authentication)); break; default: button.setText(getString(R.string.button_start_authentication)); button.setOnClickListener(startAuthenticationAction); textView.setText(getString(R.string.text_logged_out)); break; } }
private void authCramMD5() throws MessagingException { String b64Nonce = executeSimpleCommand("AUTH CRAM-MD5").replace("+ ", ""); String b64CRAM = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce); try { executeSimpleCommand(b64CRAM, true); } catch (Pop3ErrorResponse e) { throw new AuthenticationFailedException( "POP3 CRAM-MD5 authentication failed: " + e.getMessage(), e); } }
public String createToken(Authentication authentication, Boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(authority -> authority.getAuthority()) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity = new Date(now); if (rememberMe) { validity = new Date(now + this.tokenValidityInSecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInSeconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(SignatureAlgorithm.HS512, secretKey) .setExpiration(validity) .compact(); }
/** * @param authentication * @param mapping * @throws WrongTransportProtocolException * @throws WrongAuthenticationException * @throws WrongSnmpVersionException */ public SnmpV3(Authentication authentication, Mapping mapping) throws WrongTransportProtocolException, WrongAuthenticationException, WrongSnmpVersionException { if (authentication instanceof USMAuthentication) { this.authentication = authentication; this.mapping = mapping; try { if (authentication.getTransportProtocol().equalsIgnoreCase("UDP")) { transport = new DefaultUdpTransportMapping(); } else if (authentication.getTransportProtocol().equalsIgnoreCase("TCP")) { transport = new DefaultTcpTransportMapping(); } else { throw new WrongTransportProtocolException(); } } catch (IOException e) { System.err.println(e.getMessage()); } snmp = new Snmp(transport); snmp.getUSM().addUser(((USMAuthentication) authentication).getUsmUser()); } else throw new WrongAuthenticationException("USMAuthentication has to be used!"); }
private MBeanServerConnection reconnect() { try { final Map<String, Object> env = new HashMap<>(); env.put(CallbackHandler.class.getName(), Authentication.getCallbackHandler()); final JMXConnector connector = ManagementClient.this.connector = JMXConnectorFactory.connect(getRemoteJMXURL(), env); connection = connector.getMBeanServerConnection(); } catch (IOException e) { throw new RuntimeException(e); } return connection; }
/** * GET api/authentication * * <p>This action is called once the user clicks the "Sign In" button. */ @RequestMapping( value = "/api/authentication", method = {RequestMethod.GET}) public String get() throws RestException { // Instantiate the Authentication class Authentication auth = new Authentication(Util.getRestPkiClient()); // Call the Authentication startWithWebPki() method, which initiates the authentication. This // yields the token, // a 22-character case-sensitive URL-safe string, which we'll send to the page in order to pass // on the // signWithRestPki method of the Web PKI component. String token = auth.startWithWebPki(Util.getSecurityContext()); // Note: By changing the SecurityContext above you can accept only certificates from a certain // PKI, // for instance, ICP-Brasil (SecurityContext.pkiBrazil). // Return the token to the page return token; }
/** * This method needs a valid root OID to return a VariableBinding list with the sub entities. * * @param rootID - The root OID * @return - a list containing VariableBinding */ public List<VariableBinding> getSubtree(OID rootID) throws TreeEventException { TreeUtils treeUtils = new TreeUtils(snmp, new DefaultPDUFactory()); treeUtils.setMaxRepetitions(Integer.MAX_VALUE); List<TreeEvent> events = treeUtils.getSubtree(authentication.getTarget(), rootID); // Get snmpwalk result. List<VariableBinding> varBindings = new ArrayList<VariableBinding>(); for (TreeEvent event : events) { if (event != null) { if (event.isError()) throw new TreeEventException("oid [" + rootID + "] " + event.getErrorMessage()); Collections.addAll(varBindings, event.getVariableBindings()); } } return varBindings; }
private void saslAuthCramMD5(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { List<String> respList = executeSimpleCommand("AUTH CRAM-MD5"); if (respList.size() != 1) { throw new AuthenticationFailedException("Unable to negotiate CRAM-MD5"); } String b64Nonce = respList.get(0); String b64CRAMString = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce); try { executeSimpleCommand(b64CRAMString, true); } catch (MessagingException me) { throw new AuthenticationFailedException("Unable to negotiate MD5 CRAM"); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); authentication = Authentication.getInstance(getApplicationContext(), FlickrHelper.getFlickr()); button = (Button) findViewById(R.id.button_login); textView = (TextView) findViewById(R.id.text_login); ((Button) findViewById(R.id.button_templates)) .setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), TemplateActivity.class)); } }); ((Button) findViewById(R.id.button_get_photosets)) .setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { new GetPhotosetsTask().execute(); } }); photosetsAdapter = new Adapter(); ListView listView = (ListView) findViewById(R.id.listview_photosets); listView.setAdapter(photosetsAdapter); listView.setClickable(true); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { showPhotoset(photosets.get(position)); } }); updateState(); }
/** * The method get can be specified with an Array of requested OIDs. A Vector with elements of the * subclass VariableBinding will be returned. OID requested from the method GET can only return a * value. Therefore the OIDd must be a scalar and not a branch. * * @param oids - the requested OIDs * @return - a Vector with VariableBindings * @throws SNMPTimeOutException - will be thrown if a timeout with request happens * @throws PDURequestFailedException - will be thrown if an error occurs within the request * @see org.snmp4j.smi.VariableBinding */ public Vector<? extends VariableBinding> get(OID[] oids) throws SNMPTimeOutException, PDURequestFailedException { ResponseEvent responseEvent = null; Vector<? extends VariableBinding> vbs = null; try { // send the PDU responseEvent = snmp.send(createPDU(PDU.GET, oids), authentication.getTarget()); Logger.getLogger(SnmpManager.class.getName()).log(Level.INFO, responseEvent.toString()); } catch (IOException e) { System.err.println(e.getMessage()); } // extract the response PDU (could be null if timed out) if (responseEvent != null) { PDU responsePDU = responseEvent.getResponse(); if (checkResponsePDU(responsePDU)) vbs = responsePDU.getVariableBindings(); } else { throw new SNMPTimeOutException(); } return vbs; }
@Override protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { String login = successfulAuthentication.getName(); log.debug("Creating new persistent login for user {}", login); User user = userRepository.findOne(login); PersistentToken token = new PersistentToken(); token.setSeries(generateSeriesData()); token.setUser(user); token.setTokenValue(generateTokenData()); token.setTokenDate(new LocalDate()); token.setIpAddress(request.getRemoteAddr()); token.setUserAgent(request.getHeader("User-Agent")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to save persistent token ", e); } }
/** Determine if a set of credentials are valid. */ public boolean authenticate(String user, String password) throws TooManyAuthenticationAttemptsException { return authentication.authenticate(user, password); }
@Override public void onClick(View arg0) { authentication.logout(); updateState(); }
public synchronized void setPassword(String name, String password) throws IOException { if (userForName(name).passwordChangeRequired()) { regenerateToken(name); } authentication.setPassword(name, password); }
public Optional<Authentication> getAuthentication() { return authentication.isPresent() ? Optional.of(authentication) : Optional.<Authentication>absent(); }
private MBeanServerConnection getConnection() { MBeanServerConnection connection = this.connection; if (connection == null) { try { final Map<String, Object> env = new HashMap<>(); if (Authentication.username != null && !Authentication.username.isEmpty()) { // Only set this is there is a username as it disabled local authentication. env.put(CallbackHandler.class.getName(), Authentication.getCallbackHandler()); } final JMXConnector connector = this.connector = JMXConnectorFactory.connect(getRemoteJMXURL(), env); connection = this.connection = new MBeanConnectionProxy(connector.getMBeanServerConnection()); } catch (IOException e) { throw new RuntimeException(e); } } return connection; }