The federal police, in particular, is obliged to prevent unauthorised entries to the country. For this reason, its forces may check IDs on trains, stations and airports even if nothing suspicious has happened. If the police control people because of their dark skin or other features that imply their migration background, this falls under the category of "Racial Profiling". However, "Controls without individualised suspicion" ("verdachtsunabhängige Kontrollen") are, in principle, permitted under Section 22 of the Federal Police Act. That's why you should always have your ID with you. If you have been treated in a racist way or suffered from a racial harassment during a security check, you can contact a counselling centre.
There are things that police officers are not authorised to do. For instance, police officers are not allowed to search you or your home, unless you are charged with a criminal offence (§102 of the Code of Criminal Procedure or StPO) or a person who is suspected of a crime is assumed to be staying with you (§103 StPO).
If a male police officer wants to search you as a woman, you have the right to ask for a female police officer for the search. In principle, you can always refuse to make statements to the police by saying: "I do not make any remarks about this" ("Hierzu mache ich keine Angaben") or "I refuse to give a statement" ("Ich verweigere die Aussage"). You may also ask for the service ID number and the authorisation of a policeman and write the data down. With such information, you can later file a complaint against the officer. If you are arrested, you have the right to call a lawyer (emergency service 0172-3255553).