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

相关内容

热门资讯

热点推荐!wejoker辅助器... 热点推荐!wejoker辅助器可以卖,新道游戏辅助器安装包,必赢方法(有挂解密)-哔哩哔哩1、金币登...
每日必看!wepoker开脚本... 每日必看!wepoker开脚本视频,禅游辅助,专业教程(有挂技术)-哔哩哔哩1、超多福利:超高返利,...
盘点一款!hhpoker可以开... 盘点一款!hhpoker可以开透视,混沌休闲辅助,曝光教程(有挂技巧)-哔哩哔哩运hhpoker可以...
一分钟揭秘!pokerworl... 一分钟揭秘!pokerworld破解版下载,微乐自建房脚本免费下载,规律教程(有挂教程)-哔哩哔哩1...
传递经验!wepoker透视脚... 传递经验!wepoker透视脚本免费app,手游辅助软件,透明教程(有挂方法)-哔哩哔哩1、进入到w...
来一盘!hhpoker辅助靠谱... 来一盘!hhpoker辅助靠谱,pokemmo内置修改器,解说技巧(了解有挂)-哔哩哔哩1、每一步都...
重大通报!德州透视插件,新九哥... 重大通报!德州透视插件,新九哥破解版,解密教程(有挂技术)-哔哩哔哩1、超多福利:超高返利,海量正版...
揭秘!wpk插件辅助,一起宁德... 揭秘!wpk插件辅助,一起宁德钓蟹黑科技辅助软件推荐,介绍教程(有挂存在)-哔哩哔哩1、点击下载安装...
玩家必备攻略!扑克之星辅助,西... 玩家必备攻略!扑克之星辅助,西兵互娱辅助多少钱,黑科技教程(有人有挂)-哔哩哔哩1、该软件可以轻松地...
玩家必看教程!hhpoker软... 玩家必看教程!hhpoker软件安装包,张同学俱乐部有挂,可靠教程(有挂方式)-哔哩哔哩在进入张同学...