{"id":20365103,"url":"https://github.com/h3ar7b3a7/angularandspringsecurity","last_synced_at":"2026-05-04T18:32:46.555Z","repository":{"id":136744057,"uuid":"423252153","full_name":"H3AR7B3A7/AngularAndSpringSecurity","owner":"H3AR7B3A7","description":"A simple angular application with resources secured by Spring Security.","archived":false,"fork":false,"pushed_at":"2021-11-01T03:23:01.000Z","size":397,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-01T18:06:14.230Z","etag":null,"topics":["angular","spring-boot","spring-security"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/H3AR7B3A7.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-10-31T20:21:47.000Z","updated_at":"2021-11-01T04:06:03.000Z","dependencies_parsed_at":null,"dependency_job_id":"e67cc763-68cc-4312-aded-1f08c074766e","html_url":"https://github.com/H3AR7B3A7/AngularAndSpringSecurity","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/H3AR7B3A7%2FAngularAndSpringSecurity","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/H3AR7B3A7%2FAngularAndSpringSecurity/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/H3AR7B3A7%2FAngularAndSpringSecurity/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/H3AR7B3A7%2FAngularAndSpringSecurity/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/H3AR7B3A7","download_url":"https://codeload.github.com/H3AR7B3A7/AngularAndSpringSecurity/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241904719,"owners_count":20040021,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","spring-boot","spring-security"],"created_at":"2024-11-15T00:15:46.161Z","updated_at":"2026-05-04T18:32:41.520Z","avatar_url":"https://github.com/H3AR7B3A7.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Angular \u0026 Spring Security\n\nA simple angular application with resources secured by Spring Security.\n\n## Http Basic \n\n### Spring Security Configuration\n\n- We overwrite the default http security to only use HTTP Basic authentication.\n- We change the authentication entry point to prevent the browser from prompting for credentials.\n- We authorize the user to access the pages they don't need authentication for.\n- We also change the csrf token repository to use a cookie instead of a header.\n- We move our js, css and assets to their own directory, and make web security ignore them.\n- We provide an endpoint to get the Principal.\n\n```java\n@Configuration\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n    @Override\n    protected void configure(HttpSecurity http) throws Exception {\n        http\n            .httpBasic()\n                .authenticationEntryPoint((request, response, authException) \n                        -\u003e response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()))\n            .and()\n            .authorizeRequests()\n                .antMatchers(\"/index.html\", \"/\", \"/home\", \"/login\").permitAll()\n                .anyRequest().authenticated()\n            .and()\n            .csrf()\n                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());\n    }\n\n    @Override\n    public void configure(WebSecurity web) throws Exception {\n        web.ignoring().antMatchers(\"/js/**\", \"/css/**\", \"/assets/images/**\");\n    }\n}\n```\n\n### Angular Authentication \u0026 Interceptor\n\n- We create an authentication service to send a request to the endpoint we provided with Spring,\ncontaining an authorization header with 'Basic username:password' in base64 as value using the btoa() method.\nIf we get back a 200 OK, the user is authenticated, and we flip a boolean value.\n- We provide an interceptor to add additional headers.\n\n- Authentication Service:\n```typescript\n@Injectable({\n  providedIn: 'root'\n})\nexport class AuthenticationService {\n  authenticated = false\n\n  constructor(\n    private http: HttpClient\n  ) { }\n\n  authenticate(credentials: any, callback: any) {\n    const headers = new HttpHeaders(credentials ? {\n      authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password)\n    } : {})\n\n    this.http.get\u003cany\u003e('user', { headers: headers }).subscribe(response =\u003e {\n      if (response['name']) {\n        this.authenticated = true\n      } else {\n        this.authenticated = false\n      }\n      return callback \u0026\u0026 callback()\n    })\n  }\n}\n```\n\nInterceptor:\n```typescript\n@Injectable({\n  providedIn: 'root'\n})\nexport class XhrInterceptorService implements HttpInterceptor {\n\n  intercept(req: HttpRequest\u003cany\u003e, next: HttpHandler): Observable\u003cHttpEvent\u003cany\u003e\u003e {\n    const xhr = req.clone({\n      headers: req.headers.set('X-Requested-With', 'XMLHttpRequest')\n    });\n    return next.handle(xhr);\n  }\n}\n```\n\n## Form Login\n\nWith a form login, we are able to add more information to the FormData than just username and password.\nFormData is sent in the body of a POST request, instead of the header.\n\n### Spring Security Configuration\n\n```java\n@Configuration\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n    @Override\n    protected void configure(HttpSecurity http) throws Exception {\n        http\n            .csrf()\n                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())\n            .and()\n            .authorizeRequests()\n                .mvcMatchers(HttpMethod.GET,\"/index.html\", \"/\", \"/home\", \"/login\").permitAll()\n                .anyRequest().authenticated()\n            .and()\n            .formLogin()\n                .loginPage(\"/login\")\n                .loginProcessingUrl(\"/auth\")\n                .usernameParameter(\"username\")\n                .passwordParameter(\"password\")\n                .successHandler(successHandler())\n                .failureHandler(failureHandler())\n            .and()\n            .logout()\n                .logoutUrl(\"/logout\")\n                .logoutSuccessUrl(\"/\");\n    }\n\n    @Override\n    public void configure(WebSecurity web) throws Exception {\n        web.ignoring().antMatchers(\"/js/**\", \"/css/**\", \"/assets/images/**\");\n    }\n\n    private AuthenticationSuccessHandler successHandler() {\n        return (httpServletRequest, httpServletResponse, authentication) -\u003e {\n            httpServletResponse.getWriter().append(\"OK\");\n            httpServletResponse.setStatus(200);\n        };\n    }\n\n    private AuthenticationFailureHandler failureHandler() {\n        return (httpServletRequest, httpServletResponse, e) -\u003e {\n            httpServletResponse.getWriter().append(\"Authentication failure\");\n            httpServletResponse.setStatus(401);\n        };\n    }\n}\n```\n\n### Angular Authentication\n\n```typescript\n@Injectable({\n  providedIn: 'root'\n})\nexport class AuthenticationService {\n  authenticated = false\n\n  constructor(\n    private http: HttpClient,\n    private router: Router\n  ) { }\n\n  authenticate(credentials: any) {\n    var formData: FormData = new FormData()\n    formData.append('username', credentials.username)\n    formData.append('password', credentials.password)\n\n    this.http.post('auth', formData, { responseType: \"text\" }).subscribe(\n      () =\u003e {\n        this.authenticated = true\n        this.router.navigateByUrl('/')\n      },\n      () =\u003e {\n        this.authenticated = false\n      }\n    )\n  }\n\n  checkAuthenticationStatus() {\n    this.http.get\u003cany\u003e('user').subscribe(response =\u003e {\n      console.log('Checking: ' + response)\n      if (response['name']) {\n        this.authenticated = true\n      } else {\n        this.authenticated = false\n      }\n    })\n  }\n\n  logout() {\n    this.http.post('logout', {}).pipe(\n      finalize(() =\u003e {\n        this.authenticated = false;\n        this.router.navigateByUrl('/');\n      })).subscribe();\n  }\n}\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fh3ar7b3a7%2Fangularandspringsecurity","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fh3ar7b3a7%2Fangularandspringsecurity","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fh3ar7b3a7%2Fangularandspringsecurity/lists"}