1+ /*
2+ * Copyright 2025 the original author or authors.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+ package com .helioauth .passkeys .api .auth ;
18+
19+ import com .helioauth .passkeys .api .domain .ClientApplication ;
20+ import com .helioauth .passkeys .api .domain .ClientApplicationRepository ;
21+ import lombok .RequiredArgsConstructor ;
22+ import org .springframework .security .authentication .AuthenticationProvider ;
23+ import org .springframework .security .authentication .BadCredentialsException ;
24+ import org .springframework .security .core .Authentication ;
25+ import org .springframework .security .core .AuthenticationException ;
26+ import org .springframework .security .core .authority .SimpleGrantedAuthority ;
27+ import org .springframework .security .web .authentication .preauth .PreAuthenticatedAuthenticationToken ;
28+ import org .springframework .stereotype .Service ;
29+
30+ import java .util .List ;
31+ import java .util .UUID ;
32+
33+ @ Service
34+ @ RequiredArgsConstructor
35+ public class ApplicationIdAuthenticationProvider implements AuthenticationProvider {
36+
37+ private final ClientApplicationRepository clientApplicationRepository ;
38+
39+ @ Override
40+ public Authentication authenticate (Authentication authentication ) throws AuthenticationException {
41+ String appIdHeader = (String ) authentication .getPrincipal ();
42+
43+ if (appIdHeader == null || appIdHeader .isBlank ()) {
44+ throw new BadCredentialsException ("Application ID header is missing or empty" );
45+ }
46+
47+ try {
48+ UUID appId = UUID .fromString (appIdHeader );
49+ ClientApplication clientApp = clientApplicationRepository .findById (appId )
50+ .orElseThrow (() -> new BadCredentialsException ("Invalid application ID" ));
51+
52+ PreAuthenticatedAuthenticationToken authenticatedToken = new PreAuthenticatedAuthenticationToken (
53+ clientApp .getId (),
54+ clientApp ,
55+ List .of (new SimpleGrantedAuthority ("ROLE_FRONTEND_APPLICATION" ))
56+ );
57+ authenticatedToken .setDetails (clientApp );
58+
59+ return authenticatedToken ;
60+ } catch (IllegalArgumentException e ) {
61+ throw new BadCredentialsException ("Invalid application ID format" );
62+ }
63+ }
64+
65+ @ Override
66+ public boolean supports (Class <?> authentication ) {
67+ return PreAuthenticatedAuthenticationToken .class .isAssignableFrom (authentication );
68+ }
69+ }
0 commit comments