Angular前端与Spring后端安全通信。
创始人
2024-10-29 02:30:20
0

Angular前端与Spring后端之间的安全通信可以使用以下解决方案:

  1. 使用Token-Based身份验证:
    • 前端登录后,后端返回一个包含访问令牌的JWT(JSON Web Token)。
    • 前端在每个后续请求的请求头中添加该令牌。
    • 后端验证令牌的有效性并处理请求。

在Angular前端中,可以使用Angular的HttpClient模块来发送请求。以下是一个示例代码:

import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class ApiService {
  private apiUrl = 'http://localhost:8080/api';
  private headers = new HttpHeaders({ 'Content-Type': 'application/json' });

  constructor(private http: HttpClient) {}

  login(username: string, password: string): Observable {
    const body = { username: username, password: password };
    return this.http.post(`${this.apiUrl}/login`, body, { headers: this.headers });
  }

  getData(): Observable {
    const token = localStorage.getItem('token'); // 从localStorage中获取保存的令牌
    const headers = this.headers.append('Authorization', `Bearer ${token}`);
    return this.http.get(`${this.apiUrl}/data`, { headers: headers });
  }
}

在Spring后端中,可以使用Spring Security来处理身份验证和授权。以下是一个示例代码:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
            new ArrayList<>());
    }
}
@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @PostMapping("/login")
    public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtTokenProvider.generateToken(authentication);
        return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
    }

    @GetMapping("/data")
    public ResponseEntity getData() {
        // 处理请求,返回数据
        return ResponseEntity.ok("Some data");
    }
}

以上是一个简单的示例代码,实现了基于Token的身份验证和安全通信。在实际应用中,可能还需要添加更多的安全措施,例如对角色和权限的控制,以及HTTPS的使用来保护通信。

相关内容

热门资讯

透视模拟器!hhpoker智能... 透视模拟器!hhpoker智能辅助插件,新众亿免费辅助(切实是真的有挂);新众亿免费辅助是一种具有地...
透视插件!wepoker透视脚... 透视插件!wepoker透视脚本视频,闲逸有没有辅助软件功能(原来真的是有挂)1、许多玩家不知道闲逸...
透视线上!pokemomo辅助... 透视线上!pokemomo辅助软件,老友广东辅助工具(其实真的是有挂)亲,关键说明,老友广东辅助工具...
透视苹果版!we-poker辅... 透视苹果版!we-poker辅助,星悦游戏填坑辅助器(本来真的是有挂)星悦游戏填坑辅助器是一种具有地...
透视脚本!wepoker可以免... 透视脚本!wepoker可以免费玩吗,广东插件智能插件安装包免费(总是是有挂)1、让任何用户在无需广...
透视ai代打!wpk有作弊吗,... 透视ai代打!wpk有作弊吗,欢聚水鱼智能辅助(原来存在有挂);1、很好的工具软件,可以解锁游戏的欢...
透视挂!wepokerplus... 透视挂!wepokerplus辅助,微信小程序辅助有哪些(原来是真的有挂)微信小程序辅助有哪些辅助器...
辅助透视!wepoker私局代... 辅助透视!wepoker私局代打,微信小程序微乐房间怎么开挂(本来是有挂)1、下载好微信小程序微乐房...
透视工具!wepoker私人局... 透视工具!wepoker私人局透视插件,约战沙城辅助脚本(总是真的有挂);1、每一步都需要思考,不同...
透视免费!哈糖大菠萝可以开挂吗... 透视免费!哈糖大菠萝可以开挂吗,九九联盟辅助在(竟然是真的有挂)1、哈糖大菠萝可以开挂吗系统规律教程...