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的使用来保护通信。

相关内容

热门资讯

重大推荐!鄱阳翻精扑克助赢神器... 重大推荐!鄱阳翻精扑克助赢神器购买,德州小辅助app最新版本更新内容,详细有挂(有挂教学)-哔哩哔哩...
分享一款!雀神广东麻将设置方法... 分享一款!雀神广东麻将设置方法(辅助挂)太坑了确实真的有挂(有挂详情)-哔哩哔哩是由北京得雀神广东麻...
十分钟了解(pokernow德... 十分钟了解(pokernow德州)外挂透明挂辅助插件(德州)德州ai机器人(2024已更新)(哔哩哔...
分辨真假!边锋老友二打一有挂(... 分辨真假!边锋老友二打一有挂(wepOke),太坑了竟然真的有挂(有挂透明)-哔哩哔哩;(需添加指定...
透视app!边锋老友棋牌能装挂... 1、透视app!边锋老友棋牌能装挂(wepoKe),太坑了原来真的有挂(有挂详情)-哔哩哔哩;该软件...
发现玩家(Wepoke规律)外... 1、发现玩家(Wepoke规律)外挂透明挂辅助app(智能)透视辅助(2021已更新)(哔哩哔哩);...
每日必备!边锋老友棋牌免费挂,... 1、每日必备!边锋老友棋牌免费挂,hhpoker有挂,详细有挂(有挂总结)-哔哩哔哩;详细教程。2、...
科普攻略!广东雀神智能插件安装... 科普攻略!广东雀神智能插件安装可测试(透视)太坑了竟然真的有挂(有挂方法)-哔哩哔哩;一、广东雀神智...
发现一款(wepoke ai)... wepoke ai高级策略深度解析‌;发现一款(wepoke ai)外挂透明挂辅助工具(线上)发牌规...
4分钟了解!边锋游戏辅助器,德... 1、4分钟了解!边锋游戏辅助器,德州小辅助app最新版本更新内容,详细有挂(有挂规律)-哔哩哔哩。2...