Search in sources :

Example 6 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project TCSS450-Mobile-App by TCSS450-Team7-MobileApp.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMainActivity = this;
    MainActivityArgs args = MainActivityArgs.fromBundle(getIntent().getExtras());
    // Import com.auth0.android.jwt.JWT
    JWT jwt = new JWT(args.getJwt());
    // created on the web service.
    if (!jwt.isExpired(0)) {
        jwt = new JWT(args.getJwt());
    }
    new ViewModelProvider(this, new UserInfoViewModel.UserInfoViewModelFactory(args.getEmail(), jwt.toString(), args.getFirst(), args.getLast(), args.getNick(), args.getId())).get(UserInfoViewModel.class);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    // Make sure the new statements go BELOW setContentView
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.navigation_message, R.id.navigation_home, R.id.navigation_weather).build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
    mNewMessageModel = new ViewModelProvider(this).get(NewMessageCountViewModel.class);
    navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
        if (destination.getId() == R.id.navigation_message) {
            // When the user navigates to the chats page, reset the new message count.
            // This will need some extra logic for your project as it should have
            // multiple chat rooms.
            mNewMessageModel.reset();
        }
    });
    mNewMessageModel.addMessageCountObserver(this, count -> {
        BadgeDrawable badge = binding.navView.getOrCreateBadge(R.id.navigation_message);
        badge.setMaxCharacterCount(2);
        if (count > 0) {
            // new messages! update and show the notification badge.
            badge.setNumber(count);
            badge.setVisible(true);
        } else {
            // user did some action to clear the new messages, remove the badge
            badge.clearNumber();
            badge.setVisible(false);
        }
    });
}
Also used : BadgeDrawable(com.google.android.material.badge.BadgeDrawable) NewMessageCountViewModel(edu.uw.tcss450.blynch99.tcss450mobileapp.model.NewMessageCountViewModel) JWT(com.auth0.android.jwt.JWT) BottomNavigationView(com.google.android.material.bottomnavigation.BottomNavigationView) NavController(androidx.navigation.NavController) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 7 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project simple-jwt by vorbote.

the class AccessKeyUtil method Info.

/**
 * Decode the token, and you can easily get some info from
 * this token.
 *
 * @param token The token.
 * @return The decoded jwt token.
 * @throws com.auth0.jwt.exceptions.AlgorithmMismatchException     If the algorithm stated in the token's
 *                                                                 header it's not equal to the one
 *                                                                 defined in the JWTVerifier.
 * @throws com.auth0.jwt.exceptions.SignatureVerificationException If the signature is invalid.
 * @throws com.auth0.jwt.exceptions.TokenExpiredException          If the token has expired.
 * @throws com.auth0.jwt.exceptions.InvalidClaimException          If a claim contained a different value
 *                                                                 than the expected one.
 * @throws com.auth0.jwt.exceptions.JWTVerificationException       If any of the verification steps fail
 * @see JWTVerifier#verify(String)
 */
public DecodedJWT Info(String token) {
    JWTVerifier verifier;
    switch(algorithm) {
        case HS256:
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            break;
        case HS384:
            verifier = JWT.require(Algorithm.HMAC384(secret)).build();
            break;
        case HS512:
            verifier = JWT.require(Algorithm.HMAC512(secret)).build();
            break;
        default:
            // 这里理论上应该抛出异常的,但是实在是懒得做了,就先这样吧。
            // 至于其他的算法,后续再考虑加上。
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            log.error("This algorithm is not supported yet, will use HMAC256 by default.");
    }
    return verifier.verify(token);
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 8 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project UPE_2021_2_Propague by netrometro.

the class TipoParaUsuarioForm method refreshToken.

@GetMapping("/token/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        try {
            String refresh_token = authorizationHeader.substring(7);
            Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(refresh_token);
            String username = decodedJWT.getSubject();
            Usuario usuario = servico.getUsuario(username);
            String acces_token = com.auth0.jwt.JWT.create().withSubject(usuario.getEmail()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipo", usuario.getTipos().stream().map(TipoUsuario::getNome).collect(Collectors.joining())).sign(algorithm);
            // response.setHeader("acces_token", token);
            // response.setHeader("refresh_token", refresh_token);
            Map<String, String> map = new HashMap<>();
            map.put("token", acces_token);
            map.put("refresh_token", refresh_token);
            response.setContentType(APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            response.setHeader("error", e.getMessage());
            response.setStatus(403);
            Map<String, String> map = new HashMap<>();
            map.put("error", e.getMessage());
            response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), map);
        }
    } else {
        throw new RuntimeException("Refresh token is missing");
    }
}
Also used : TipoUsuario(br.com.propague.api.model.TipoUsuario) Usuario(br.com.propague.api.model.Usuario) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) IOException(java.io.IOException) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 9 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project Team_BbungCles_Devnity_BE by prgrms-web-devcourse.

the class Jwt method sign.

public String sign(Claims claims) {
    Date now = new Date();
    JWTCreator.Builder builder = com.auth0.jwt.JWT.create();
    builder.withIssuer(issuer);
    builder.withIssuedAt(now);
    if (expirySeconds > 0) {
        builder.withExpiresAt(new Date(now.getTime() + expirySeconds * 1_000L));
    }
    builder.withClaim("userId", claims.userId);
    builder.withClaim("email", claims.email);
    builder.withClaim("role", claims.role);
    return builder.sign(algorithm);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Date(java.util.Date)

Example 10 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project cryptography by norkator.

the class JWT method createECDSA256Jwt.

/**
 * Create elliptic curve based JWT
 *
 * @param privatePem of EC keypair
 * @param issuer     party name
 * @return json web token
 * @throws JWTCreationException if jwt creation fails
 */
public static String createECDSA256Jwt(String privatePem, String issuer) throws InvalidKeySpecException, NoSuchAlgorithmException {
    ECKey privateKey = (ECKey) PEMToKey.getPemPrivateKey(privatePem, "ECDSA");
    Algorithm algorithm = Algorithm.ECDSA256(privateKey);
    return com.auth0.jwt.JWT.create().withIssuer(issuer).withClaim("test claim", "test claim value").sign(algorithm);
}
Also used : ECKey(java.security.interfaces.ECKey) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)8 TokenRequest (com.auth0.net.TokenRequest)8 Test (org.junit.jupiter.api.Test)8 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)8 TokenHolder (com.auth0.json.auth.TokenHolder)7 Date (java.util.Date)7 HashMap (java.util.HashMap)7 JWTCreator (com.auth0.jwt.JWTCreator)6 JWTVerifier (com.auth0.jwt.JWTVerifier)6 Cookie (javax.servlet.http.Cookie)6 ECKey (java.security.interfaces.ECKey)3 AuthorizeUrlBuilder (com.auth0.client.auth.AuthorizeUrlBuilder)2 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 ViewModelProvider (androidx.lifecycle.ViewModelProvider)1 NavController (androidx.navigation.NavController)1 TipoUsuario (br.com.propague.api.model.TipoUsuario)1 Usuario (br.com.propague.api.model.Usuario)1 JWT (com.auth0.android.jwt.JWT)1 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)1